精华内容
下载资源
问答
  • Android 获取经纬度

    2021-01-03 22:28:53
    Android 获取 经纬度 在百度上查了算是两天吧,什么样的方法都有,wifi定位,gps定位,等等, 首先看到的是代码及其多,各种配置,后来代码一运行各种报错,很烦,于是自己用高德sdk写了个,是公司需要,需求写完了...
  • android获取经纬度

    2016-06-06 22:42:12
    android获取经纬度,只是单纯的经纬度,没有其他功能,因为在网上找了好久没有直接的例子,所以上次一个,希望能帮到大家。
  • Android获取经纬度

    2015-11-13 10:37:15
    Android获取经纬度

    机子自带GPS:

    private void getlocationFromGPS(){
    		Criteria criteria = new Criteria();
    	        criteria.setAccuracy(Criteria.ACCURACY_FINE);//高精度
    	        criteria.setAltitudeRequired(false);//不要求海拔
    	        criteria.setBearingRequired(false);//不要求方位
    	        criteria.setCostAllowed(false);//不允许有花费
    	        criteria.setPowerRequirement(Criteria.POWER_LOW);//低功耗
    	        
    	      //获得位置服务的名称
    	        String serviceName = this.LOCATION_SERVICE;
    	        //获得位置服务的管理对象
    	        LocationManager locationManager = (LocationManager)getSystemService(serviceName);
    	      //从可用的位置提供器中,匹配以上标准的最佳提供器
    	        String provider = locationManager.getBestProvider(criteria, true);
    	        // 通过GPS获取定位的位置数据
    	        location = locationManager.getLastKnownLocation(provider);
    	        updateToNewLocation(location);
    
    	            /**服务管理对象的监听器*/
    	            //参数1:定位的方式   参数2:监听更新间隔时间(ms)  参数3:监听更新的距离(m) 参数4:监听的方法
    	            locationManager.requestLocationUpdates(provider, 2000, 1, new LocationListener() {
    
    	                public void onStatusChanged(String provider, int status, Bundle extras) {
    	                }
    	                public void onProviderEnabled(String provider) {
    	                }
    	                public void onProviderDisabled(String provider) {
    	                }
    	                public void onLocationChanged(Location location) {
    	                    updateToNewLocation(location);
    	                }
    	            });
    	 }


    private void updateToNewLocation(Location location) {
    
    		    
    		    tv1 = (TextView) this.findViewById(R.id.tv_setting_adress);
    		    if (location != null) {
    		        latitude = location.getLatitude();
    		        longitude= location.getLongitude();
    		        tv1.setText("经纬度为: "+"维度:" +  latitude+ ",经度; " + longitude);
    		          
    		    } else {
    		        tv1.setText("无法获取地理信息");
    		        getlocationFrombaiduSDK();//当设备在室内往往GPS无法正常工作,这时候可以用baiduSDKAPI来获取位置服务
    		        
    		        locationClient.start();//开启baiduSDK服务
    		        
    	            /*
    	             *当所设的整数值大于等于1000(ms)时,定位SDK内部使用定时定位模式。
    	             *调用requestLocation( )后,每隔设定的时间,定位SDK就会进行一次定位。
    	             *如果定位SDK根据定位依据发现位置没有发生变化,就不会发起网络请求,
    	             *返回上一次定位的结果;如果发现位置改变,就进行网络请求进行定位,得到新的定位结果。
    	             *定时定位时,调用一次requestLocation,会定时监听到定位结果。
    	             */
    	            locationClient.requestLocation();
    	            
    		        //test2();
    		    }
    
    		}

    baiduSDKAPI:

    1. 登录百度LBS Android SDK下载中下载Android SDK全部功能的开发包,您可以结合自身需求,自定义选择业务功能,进行打包下载。
    2. 在使用之前,您需要先申请密钥,且密钥和应用证书和包名绑定。具体配置可在下载中心查看
    3.将下载的jar包放进libs下

    4.点击鼠标右键



    void getlocationFrombaiduSDK(){
    		 
    		 locationClient = new LocationClient(this);
    		//设置定位条件
    	     LocationClientOption option = new LocationClientOption();
    	     option.setOpenGps(true);        //是否打开GPS
    	     option.setCoorType("bd09ll");       //设置返回值的坐标类型。
    	     option.setPriority(LocationClientOption.NetWorkFirst);  //设置定位优先级
    	     option.setProdName("LocationDemo"); //设置产品线名称。强烈建议您使用自定义的产品线名称,方便我们以后为您提供更高效准确的定位服务。
    	     option.setScanSpan(UPDATE_TIME);    //设置定时定位的时间间隔。单位毫秒
    	     locationClient.setLocOption(option);
    	   //注册位置监听器
    	        locationClient.registerLocationListener(new BDLocationListener() {
    	             
    	            @Override
    	            public void onReceiveLocation(BDLocation location1) {
    	                // TODO Auto-generated method stub
    	                if (location1 == null) {
    	                	tv1.setText("无法获取地理信息");
    	                    return;
    	                }
    	                
    	                
    	                latitude = location1.getLatitude();
    			        longitude= location1.getLongitude();
    			        LOCATION_COUTNS ++;
    			        tv1.setText("经纬度为: "+"维度:" +  latitude+ ",经度; " + longitude + "fs" +LOCATION_COUTNS);
    			        
    			        Thread thread=new Thread(new Runnable()  
    	                {  
    	                   @Override  
    	                    public void run()  
    	                    {                  	   
    	       	    		Message msg = new Message();  
    	       	    		msg.what = sendGPS();;       	    		       	    		
    	       	    		handler.sendMessage(msg); 
    	                    }  
    	                });  	    	    
    			        thread.start();
    	            }
    	            public void onReceivePoi(BDLocation location) {
    	            }
    
    	        });	        
    	 }


    当然别忘了Manifest.xml里加上权限

     <uses-permission android:name="android.permission.INTERNET" /><!-- 这个权限用于进行网络连接-->
        
    <!-- 这个权限用于进行网络定位-->
    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"></uses-permission>
    <!-- 这个权限用于访问GPS定位-->
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"></uses-permission>
    <!-- 用于访问wifi网络信息,wifi信息会用于进行网络定位-->
    <uses-permission android:name="android.permission.ACCESS_WIFI_STATE"></uses-permission>
    <!-- 获取运营商信息,用于支持提供运营商信息相关的接口-->
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"></uses-permission>
    <!-- 这个权限用于获取wifi的获取权限,wifi信息会用来进行网络定位-->
    <uses-permission android:name="android.permission.CHANGE_WIFI_STATE"></uses-permission>
    <!-- 用于读取手机当前的状态-->
    <uses-permission android:name="android.permission.READ_PHONE_STATE"></uses-permission>
    <!-- 写入扩展存储,向扩展卡写入数据,用于写入离线定位数据-->
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"></uses-permission>
    <!-- 访问网络,网络定位需要上网-->
    <uses-permission android:name="android.permission.INTERNET" />
    <!-- SD卡读取权限,用户写入离线定位数据-->
    <uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS"></uses-permission>



    
    
    展开全文
  • android 获取经纬度

    2019-08-21 14:13:30
    我反驳的理由:如果google没有对经纬度获取做了特别处理,为什么要开一个获取经纬度方法而不用android自带的jar方法,包括百度,高德也是一样;如果说本地API可以百分百获取到以及非常精确,...

    我把这个获取经纬度的类分享出来的原因:
    1、我说了android手机获取本地GPS的经纬度有些手机不一定有值;他一直坚信google可以拿到;为什么就获取不到值;一直说让我就研究google定位的源代码;我反驳的理由:如果google没有对经纬度获取做了特别处理,为什么要开一个获取经纬度方法而不用android自带的jar方法,包括百度,高德也是一样;如果说本地API可以百分百获取到以及非常精确,这些第三方又不傻,他们就直接开启一个通过经纬度获取城市信息API即可,何必多开一个定位获取经纬度功能,多此一举;而且google的源代码等您看完,黄花菜都凉了
    2、本来这个APP就是给国外用的,使用google获取经纬度就是免费的;硬要用获取本地GPS
    3、在中国使用google获取经纬度慢,这个锅丢给前台;我在国外使用都是非常快;、
    4、真的很无语,无法与架构师沟通;也许我菜吧

    package com.xinyi.morefun.morefun.location;
    
    import android.Manifest;
    import android.app.Activity;
    import android.content.Context;
    import android.content.pm.PackageManager;
    import android.location.Location;
    import android.location.LocationManager;
    import android.os.Bundle;
    import android.support.annotation.NonNull;
    import android.support.annotation.Nullable;
    import android.support.v4.app.ActivityCompat;
    
    import com.google.android.gms.common.ConnectionResult;
    import com.google.android.gms.common.GoogleApiAvailability;
    import com.google.android.gms.common.api.GoogleApiClient;
    import com.google.android.gms.common.api.PendingResult;
    import com.google.android.gms.common.api.ResultCallback;
    import com.google.android.gms.common.api.Status;
    import com.google.android.gms.location.LocationListener;
    import com.google.android.gms.location.LocationRequest;
    import com.google.android.gms.location.LocationServices;
    import com.google.android.gms.location.LocationSettingsRequest;
    import com.google.android.gms.location.LocationSettingsResult;
    import com.google.android.gms.location.LocationSettingsStates;
    import com.google.android.gms.location.LocationSettingsStatusCodes;
    import com.google.android.gms.location.places.PlaceLikelihoodBuffer;
    import com.google.android.gms.location.places.Places;
    import com.xinyi.morefun.library.kallehttp.HttpManager;
    import com.xinyi.morefun.library.kallehttp.httpInterface.HttpListener;
    import com.xinyi.morefun.library.model.GoogleLocationModel;
    import com.xinyi.morefun.library.util.JsonUtil;
    import com.xinyi.morefun.library.util.LogUtil;
    import com.xinyi.morefun.library.util2.BugUtil;
    import com.xinyi.morefun.library.util2.StringUtil;
    import com.xinyi.morefun.morefun.AppUserInfo;
    import com.xinyi.morefun.morefun.http2.HttpConfig;
    import com.xinyi.morefun.morefun.http2.HttpParamUtil;
    
    import java.util.HashMap;
    import java.util.List;
    import java.util.Map;
    
    public class GoogleLocationManager implements GoogleApiClient.OnConnectionFailedListener, GoogleApiClient.ConnectionCallbacks {
        private static volatile GoogleLocationManager googleLocationManager;
    
        private GoogleApiClient mGoogleApiClient;
    
        private LocationRequest locationRequest;
    
        private Context context;
    
        private String lng;
    
        private String lat;
    
        private OnGoogleLocationListener onGoogleLocationListener;
    
    
        private GoogleLocationManager() {
    
        }
    
        public static GoogleLocationManager getInstanceFor() {
            if (null == googleLocationManager) {
                synchronized (GoogleLocationManager.class) {
                    if (googleLocationManager == null) {
                        googleLocationManager = new GoogleLocationManager();
                    }
                }
            }
            return googleLocationManager;
        }
    
        /**
         * 是否支持Google服务
         * @return
         */
        public boolean isGooglePlayServiceAvailable() {
            int status = GoogleApiAvailability.getInstance().isGooglePlayServicesAvailable(context);
            if (status == ConnectionResult.SUCCESS) {
                return true;
            } else {
                return false;
            }
        }
    
        /**
         * 本地定位,优先本地定位,然后谷歌;谷歌定位慢也关前台事情,真的很无语;前台永远背锅,加速转后台中
         * @param
         * @param onGoogleLocationListener
         */
        public void googleLocation(Context mContext, OnGoogleLocationListener onGoogleLocationListener) {
            this.context = mContext;
            this.onGoogleLocationListener = onGoogleLocationListener;
            try {
                if (ActivityCompat.checkSelfPermission(context, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(context, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                    // TODO: Consider calling
                    //  ActivityCompat#requestPermissions
                    // here to request the missing permissions, and then overriding
                    // public void onRequestPermissionsResult(int requestCode, String[] permissions,
                    // int[] grantResults)
                    // to handle the case where the user grants the permission. See the documentation
                    // for ActivityCompat#requestPermissions for more details.
                    return;
                }
    
                android.location.LocationManager locationManager = (android.location.LocationManager) context.getSystemService( Context.LOCATION_SERVICE );
                Location location=locationManager.getLastKnownLocation(android.location.LocationManager.GPS_PROVIDER);
                if(location==null){
                    location=locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
                }
                if(location!=null){
                    lng = location.getLongitude() + "";
                    lat = location.getLatitude() + "";
                    LogUtil.getInstanceFor().e("本地经纬度:"+lng+" , "+lat);
                    AppUserInfo.getInstanceFor().saveLat(lat);
                    AppUserInfo.getInstanceFor().saveLng(lng);
                    if(isRequestLocation()){
                        onGoogleLocationListener.onGoogleLocationFailCallback("本地定位失败,  错误信息:");
                    }
                }else{
                    LogUtil.getInstanceFor().e("本地定位失败");
                    //别问我为啥加这个,如果遍历都拿不到经纬度;也别找我,测试得知还是有设备得不到经纬度;懒得解释;
                    List<String> providers = locationManager.getProviders(true);
                    for (String provider : providers) {
                        Location l = locationManager.getLastKnownLocation(provider);
                        if (l == null) {
                            continue;
                        }
                        if (location == null || l.getAccuracy() < location.getAccuracy()) {
                            // Found best last known location: %s", l);
                            location = l;
                        }
                    }
                    if(location==null){
                        googleLocation2(context,onGoogleLocationListener);
                    }else{
                        LogUtil.getInstanceFor().e("本地经纬度:"+lng+" , "+lat);
                        AppUserInfo.getInstanceFor().saveLat(lat);
                        AppUserInfo.getInstanceFor().saveLng(lng);
                        if(isRequestLocation()){
                            onGoogleLocationListener.onGoogleLocationFailCallback("本地定位失败,  错误信息:");
                        }
                    }
    
    
                }
            }catch (Exception e){
                LogUtil.getInstanceFor().e(""+e.getMessage());
                onGoogleLocationListener.onGoogleLocationFailCallback("本地定位失败,  错误信息:");
            }
        }
    
    
        /**
         *
         * @param mContext
         * @param onGoogleLocationListener
         * cityInfos[0] = addressComponentsBean.getLong_name();
         *                                 cityInfos[1] = resultsBean.getFormatted_address();
         *                                 cityInfos[2] = resultsBean.getGeometry().getLocation().getLat()+"";
         *                                 cityInfos[3] = resultsBean.getGeometry().getLocation().getLng()+"";
         */
        public void googleLocation2(Context mContext, OnGoogleLocationListener onGoogleLocationListener) {
            this.context = mContext;
            this.onGoogleLocationListener = onGoogleLocationListener;
            if (mGoogleApiClient != null) {
    
                if (mGoogleApiClient.isConnected()) {
                    mGoogleApiClient.disconnect();
                    mGoogleApiClient.connect();
                }
                LogUtil.getInstanceFor().e("google position res");
    //            return;
            }
            LogUtil.getInstanceFor().e("google position");
            mGoogleApiClient = new GoogleApiClient
                    .Builder(context)
                    .addApi(Places.GEO_DATA_API)
                    .addApi(Places.PLACE_DETECTION_API)
                    .addApi(LocationServices.API)
                    .addOnConnectionFailedListener(this)
                    .addConnectionCallbacks(this)
                    .build();
            mGoogleApiClient.connect();
    
            locationRequest = LocationRequest.create();
            locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
            locationRequest.setInterval(30 * 1000);
            locationRequest.setFastestInterval(5 * 1000);
            LocationSettingsRequest.Builder builder = new LocationSettingsRequest.Builder()
                    .addLocationRequest(locationRequest);
    
            //**************************
            builder.setAlwaysShow(true); //this is the key ingredient
            //**************************
    
            PendingResult<LocationSettingsResult> result =
                    LocationServices.SettingsApi.checkLocationSettings(mGoogleApiClient, builder.build());
            result.setResultCallback(new ResultCallback<LocationSettingsResult>() {
                @Override
                public void onResult(LocationSettingsResult result) {
                    Status status = result.getStatus();
                    LocationSettingsStates state = result.getLocationSettingsStates();
                    switch (status.getStatusCode()) {
                        case LocationSettingsStatusCodes.SUCCESS:
                            if (ActivityCompat.checkSelfPermission(context, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(context, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                                return;
                            }
                            LogUtil.getInstanceFor().e("定位开启:SUCCESS: ");
                            break;
                        case LocationSettingsStatusCodes.RESOLUTION_REQUIRED:
                            try {
                                status.startResolutionForResult(
                                        (Activity) context, 999);
                                LogUtil.getInstanceFor().e("定位开启:RESOLUTION_REQUIRED: ");
                                LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, locationRequest, new LocationListener() {
                                    @Override
                                    public void onLocationChanged(Location location) {
                                        LogUtil.getInstanceFor().e(location.getLatitude() + " onLocationChanged");
                                        lat = location.getLatitude() + "";
                                        lng = location.getLongitude() + "";
                                        AppUserInfo.getInstanceFor().saveLat(lat);
                                        AppUserInfo.getInstanceFor().saveLng(lng);
                                    }
                                });
                            } catch (Exception e) {
                                // Ignore the error.
                            }
                            break;
                        case LocationSettingsStatusCodes.SETTINGS_CHANGE_UNAVAILABLE:
    
                            LogUtil.getInstanceFor().e("定位:SETTINGS_CAANCE_UNAVALABLE:");
                            break;
                    }
                }
            });
        }
    
        @Override
        public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {
            LogUtil.getInstanceFor().e("定位失败,谷歌连接失败,错误码:" );
            BugUtil.getInstanceFor().saveOtherErrorMsg("定位失败,谷歌连接失败,错误码:" + connectionResult.getErrorCode() + "  ,  错误信息:" + connectionResult.getErrorMessage());
    //        onGoogleLocationListener.onGoogleLocationFailCallback("定位连接成功,但是谷歌没有给出数据");
            try {
                if (ActivityCompat.checkSelfPermission(context, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(context, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                    // TODO: Consider calling
                    //    ActivityCompat#requestPermissions
                    // here to request the missing permissions, and then overriding
                    //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
                    //                                          int[] grantResults)
                    // to handle the case where the user grants the permission. See the documentation
                    // for ActivityCompat#requestPermissions for more details.
                    return;
                }
    
                android.location.LocationManager locationManager = (android.location.LocationManager) context.getSystemService( Context.LOCATION_SERVICE );
                Location location=locationManager.getLastKnownLocation(android.location.LocationManager.GPS_PROVIDER);
                if(location==null){
                    location=locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
                }
    
                if(location==null){
                    location=locationManager.getLastKnownLocation(LocationManager.PASSIVE_PROVIDER);
                }
    
                if(location!=null){
                    lng = location.getLongitude() + "";
                    lat = location.getLatitude() + "";
                    AppUserInfo.getInstanceFor().saveLat(lat);
                    AppUserInfo.getInstanceFor().saveLng(lng);
                    LogUtil.getInstanceFor().e("本地经纬度:"+lng+" , "+lat);
                }else{
                    List<String> providers = locationManager.getProviders(true);
                    for (String provider : providers) {
                        Location l = locationManager.getLastKnownLocation(provider);
                        if (l == null) {
                            continue;
                        }
                        if (location == null || l.getAccuracy() < location.getAccuracy()) {
                            // Found best last known location: %s", l);
                            location = l;
                        }
                    }
                    if(location!=null){
                        lng = location.getLongitude() + "";
                        lat = location.getLatitude() + "";
                        AppUserInfo.getInstanceFor().saveLat(lat);
                        AppUserInfo.getInstanceFor().saveLng(lng);
                        LogUtil.getInstanceFor().e("本地经纬度:"+lng+" , "+lat);
                    }
                }
            }catch (Exception e){
                LogUtil.getInstanceFor().e(""+e.getMessage());
            }
    
            if(isRequestLocation()){
                onGoogleLocationListener.onGoogleLocationFailCallback("定位失败,谷歌连接失败,错误码:" + connectionResult.getErrorCode() + "  ,  错误信息:" + connectionResult.getErrorMessage());
            }
        }
    
    
    
    
        @Override
        public void onConnected(@Nullable Bundle bundle) {
            LogUtil.getInstanceFor().e("onConnected google");
            if (ActivityCompat.checkSelfPermission(context, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                return;
            }
            PendingResult<PlaceLikelihoodBuffer> result = Places.PlaceDetectionApi
                    .getCurrentPlace(mGoogleApiClient, null);
            result.setResultCallback(new ResultCallback<PlaceLikelihoodBuffer>() {
                @Override
                public void onResult(PlaceLikelihoodBuffer likelyPlaces) {
                    if (likelyPlaces != null && likelyPlaces.getCount() != 0) {//placeLikelihood.getLikelihood()越大越接近您的位置
                        //您要进行的业务操作
                        lng = likelyPlaces.get(0).getPlace().getLatLng().longitude + "";
                        lat = likelyPlaces.get(0).getPlace().getLatLng().latitude + "";
                        AppUserInfo.getInstanceFor().saveLat(lat);
                        AppUserInfo.getInstanceFor().saveLng(lng);
                        getPHPLocationResult(context,lat,lng,onGoogleLocationListener);
                    } else {//定位失败
                        LogUtil.getInstanceFor().e("定位连接成功,但是谷歌没有给出数据");
                        BugUtil.getInstanceFor().saveOtherErrorMsg("定位连接成功,但是谷歌没有给出数据");
    
                        try {
                            if (ActivityCompat.checkSelfPermission(context, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(context, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                                // TODO: Consider calling
                                //    ActivityCompat#requestPermissions
                                // here to request the missing permissions, and then overriding
                                //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
                                //                                          int[] grantResults)
                                // to handle the case where the user grants the permission. See the documentation
                                // for ActivityCompat#requestPermissions for more details.
                                return;
                            }
                            android.location.LocationManager locationManager = (android.location.LocationManager) context.getSystemService( Context.LOCATION_SERVICE );
                            Location location=locationManager.getLastKnownLocation(android.location.LocationManager.GPS_PROVIDER);
                            if(location==null){
                               location=locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
                            }
    
                            if(location==null){
                                location=locationManager.getLastKnownLocation(LocationManager.PASSIVE_PROVIDER);
                            }
    
                            if(location!=null){
                                lng = location.getLongitude() + "";
                                lat = location.getLatitude() + "";
                                AppUserInfo.getInstanceFor().saveLat(lat);
                                AppUserInfo.getInstanceFor().saveLng(lng);
                            }else{
                                List<String> providers = locationManager.getProviders(true);
                                for (String provider : providers) {
                                    Location l = locationManager.getLastKnownLocation(provider);
                                    if (l == null) {
                                        continue;
                                    }
                                    if (location == null || l.getAccuracy() < location.getAccuracy()) {
                                        // Found best last known location: %s", l);
                                        location = l;
                                    }
                                }
                                if(location!=null){
                                    lng = location.getLongitude() + "";
                                    lat = location.getLatitude() + "";
                                    AppUserInfo.getInstanceFor().saveLat(lat);
                                    AppUserInfo.getInstanceFor().saveLng(lng);
                                    LogUtil.getInstanceFor().e("本地经纬度:"+lng+" , "+lat);
                                }
                            }
    
    
                        }catch (Exception e){
                            LogUtil.getInstanceFor().e(""+e.getMessage());
                        }
    
                        if(isRequestLocation()){
                            onGoogleLocationListener.onGoogleLocationFailCallback("定位连接成功,但是谷歌没有给出数据");
                        }
    
                    }
                }
            });
        }
    
        public boolean isRequestLocation(){
            if(!StringUtil.getInstanceFor().isEmpty(AppUserInfo.getInstanceFor().getLat())&&!StringUtil.getInstanceFor().isEmpty(AppUserInfo.getInstanceFor().getLng())){
                if(AppUserInfo.getInstanceFor().getLat().length()<4&&AppUserInfo.getInstanceFor().getLng().length()<4){
                    return true;
                }
                getPHPLocationResult(context,AppUserInfo.getInstanceFor().getLat(),AppUserInfo.getInstanceFor().getLng(),onGoogleLocationListener);
                return false;
            }
            return true;
        }
    
    
    
        @Override
        public void onConnectionSuspended(int i) {
            LogUtil.getInstanceFor().e("onConnectionSuspended: "+i);
        }
    
    
        /**
         * 获取城市信息
         * @param context 上下文
         * @param latlng 经纬度 中间要用逗号分割
         * @param onGoogleLocationListener  回调接口
         */
        public void getLocationResult(Context context, final String latlng, final OnGoogleLocationListener onGoogleLocationListener){
            Map<String,Object> params = new HashMap<>();
            params.put("latlng",latlng);
            params.put("key","您的googlekey");
            params.put("language","en-us");
            HttpManager.getInstanceFor(context).httpGetAPI(HttpConfig.GOOGLEBYCITY, params, new HttpListener() {
                @Override
                public void onHttpResult(Object data,String msg) {
                    String[] str = getJsonToCityInfoLocality((String) data);
                    if(str!=null){
                        LogUtil.getInstanceFor().e("定位成功:"+str[0]);
                        AppUserInfo.getInstanceFor().savaCity(str[0]);
                        onGoogleLocationListener.onGoogleLocationSuccessCallback(str[0],str[1],str[2],str[3]);
                    }else{//定位失败
                        BugUtil.getInstanceFor().saveOtherErrorMsg("定位成功,但是谷歌给的JSON无法找到地址信息"+latlng);
                        onGoogleLocationListener.onGoogleLocationFailCallback("定位成功,但是谷歌给的JSON无法找到地址信息");
                    }
                }
    
                @Override
                public void onHttpFail(String code, String msg) {//不会执行
    
                }
    
                @Override
                public void onHttpError(String errormsg) {//定位失败
                    LogUtil.getInstanceFor().e("定位成功,但是谷歌获取城市信息的接口请求失败"+errormsg);
                    BugUtil.getInstanceFor().saveOtherErrorMsg("定位成功,但是谷歌获取城市信息的接口请求失败"+errormsg);
                    onGoogleLocationListener.onGoogleLocationFailCallback("定位成功,但是谷歌获取城市信息的接口请求失败"+errormsg);
                }
            },null);
        }
    
    //    cityInfos[0] = addressComponentsBean.getLong_name();
    //    cityInfos[1] = resultsBean.getFormatted_address();
    //    cityInfos[2] = resultsBean.getGeometry().getLocation().getLat()+"";
    //    cityInfos[3] = resultsBean.getGeometry().getLocation().getLng()+"";
    
        /**
         * PHP通过经纬度获取城市名
         * @param onGoogleLocationListener
         */
        public void getPHPLocationResult(Context mContext,String lat,String lng,OnGoogleLocationListener onGoogleLocationListener) {
                this.context = mContext;
                Map<String,Object> params = new HashMap<>();
                params.put("lat",lat);
                params.put("lng",lng);
                HttpManager.getInstanceFor(context).httpGetAPI(HttpConfig.GETCITYNAME, HttpParamUtil.getInstanceFor().postPHPValidationParam(params), new HttpListener() {
                    @Override
                    public void onHttpResult(Object data,String msg) {
                        if(data instanceof ApiLocationResult){
                            ApiLocationResult apiLocationResult = (ApiLocationResult) data;
                            onGoogleLocationListener.onGoogleLocationSuccessCallback(apiLocationResult.getCityname(),apiLocationResult.getFormatted_address(),lat,lng);
                        }else{
                            getLocationResult(context, lat+","+lng,onGoogleLocationListener);
                        }
                    }
    
                    @Override
                    public void onHttpFail(String code,String msg) {
                        getLocationResult(context, lat+","+lng,onGoogleLocationListener);
                    }
    
                    @Override
                    public void onHttpError(String errormsg) {
                        onGoogleLocationListener.onGoogleLocationFailCallback("PHP网络请求失败");
                    }
                },ApiLocationResult.class);
            }
    
            public class ApiLocationResult{
    
                /**
                 * cityname : Guangzhou Shi
                 */
    
                private String cityname;
    
                private String formatted_address;
    
                public String getFormatted_address() {
                    return formatted_address;
                }
    
                public void setFormatted_address(String formatted_address) {
                    this.formatted_address = formatted_address;
                }
    
                public String getCityname() {
                    return cityname;
                }
    
                public void setCityname(String cityname) {
                    this.cityname = cityname;
                }
            }
    
        /**
         * 计算两点的曲线距离以及时间
         * @param slatlng 开始地点
         * @param elatlng 结束地点
         * @param onGoogleRouleListener 回调;第一个参数是距离m,第一个参数是时间s
         */
        public void getRouteDistance(String slatlng, String elatlng, final OnGoogleRouleListener onGoogleRouleListener){
            LogUtil.getInstanceFor().e("计算曲线距离");
            Map<String,Object> params = new HashMap<>();
            params.put("units","metric");
            params.put("key","您的googlekey");
            params.put("language","en-us");
            params.put("origins",slatlng);
            params.put("destinations",elatlng);
            HttpManager.getInstanceFor(context).httpGetAPI(HttpConfig.GOOGLEQXJL, params, new HttpListener() {
                @Override
                public void onHttpResult(Object data,String msg) {
                    try{
                        RouteDistanceModel routeDistanceModel = (RouteDistanceModel) JsonUtil.getInstanceFor().parseObject((String) data,RouteDistanceModel.class);
                        if(StringUtil.getInstanceFor().equalsUL(routeDistanceModel.getStatus(),"OK")){
                            if(routeDistanceModel.getRows()!=null&&routeDistanceModel.getRows().size()!=0&&routeDistanceModel.getRows().get(0).getElements()!=null&&routeDistanceModel.getRows().get(0).getElements().size()!=0){
                                int distance = routeDistanceModel.getRows().get(0).getElements().get(0).getDistance().getValue();
                                int duration = routeDistanceModel.getRows().get(0).getElements().get(0).getDuration().getValue();
                                onGoogleRouleListener.onGoogleRouleSuccessCallback(distance,duration);
                            }else{
                                BugUtil.getInstanceFor().saveOtherErrorMsg("请求计算距离接口成功,但是谷歌没有给数据"+data);
                                onGoogleRouleListener.onGoogleRouleFailCallback("请求计算距离接口成功,但是谷歌没有给数据");
                            }
                        }else{
                            BugUtil.getInstanceFor().saveOtherErrorMsg("请求计算距离接口成功,但是谷歌给的数据是失败的"+data);
                            onGoogleRouleListener.onGoogleRouleFailCallback("请求计算距离接口成功,但是谷歌给的数据是失败的");
                        }
                    }catch (Exception e){
                        BugUtil.getInstanceFor().saveOtherErrorMsg("定位成功,但是谷歌获取城市信息的接口请求失败"+e.getMessage());
                        onGoogleLocationListener.onGoogleLocationFailCallback("定位成功,但是谷歌获取城市信息的接口请求失败"+e.getMessage());
                    }
    
                }
    
                @Override
                public void onHttpFail(String code, String msg) {//不会执行
    
                }
    
                @Override
                public void onHttpError(String errormsg) {//定位失败
                    BugUtil.getInstanceFor().saveOtherErrorMsg("定位成功,但是谷歌获取城市信息的接口请求失败"+errormsg);
                    onGoogleLocationListener.onGoogleLocationFailCallback("定位成功,但是谷歌获取城市信息的接口请求失败"+errormsg);
                }
            },null);
        }
    
    //    /**
    //     * 获取谷歌城市信息 0 城市名  1  详细地址 2 纬度  3 经度
    //     * @param json
    //     * @return
    //     */
    //    @Deprecated
    //    private String[] getJsonToCityInfo(String json){
    //        String[] cityInfos = new String[4];
    //        GoogleLocationModel googleLocationModel = (GoogleLocationModel) JsonUtil.getInstanceFor().parseObject(json,GoogleLocationModel.class);
    //        if(googleLocationModel == null){
    //            return null;
    //        }else{
    //            if(googleLocationModel.getStatus().equals("OK")){
    //                for (GoogleLocationModel.ResultsBean resultsBean:googleLocationModel.getResults()){
    //                    for(GoogleLocationModel.ResultsBean.AddressComponentsBean addressComponentsBean:resultsBean.getAddress_components()){
    //                        for(String type:addressComponentsBean.getTypes()){
    //                            if(type.equals("locality")){
    //                                cityInfos[0] = addressComponentsBean.getLong_name();
    //                                cityInfos[1] = resultsBean.getFormatted_address();
    //                                cityInfos[2] = resultsBean.getGeometry().getLocation().getLat()+"";
    //                                cityInfos[3] = resultsBean.getGeometry().getLocation().getLng()+"";
    //                                return cityInfos;
    //                            }else if(type.equals("administrative_area_level_2")){
    //                                cityInfos[0] = addressComponentsBean.getLong_name();
    //                                cityInfos[1] = resultsBean.getFormatted_address();
    //                                cityInfos[2] = resultsBean.getGeometry().getLocation().getLat()+"";
    //                                cityInfos[3] = resultsBean.getGeometry().getLocation().getLng()+"";
    //                                return cityInfos;
    //                            }else if(type.equals("administrative_area_level_1")){
    //                                cityInfos[0] = addressComponentsBean.getLong_name();
    //                                cityInfos[1] = resultsBean.getFormatted_address();
    //                                cityInfos[2] = resultsBean.getGeometry().getLocation().getLat()+"";
    //                                cityInfos[3] = resultsBean.getGeometry().getLocation().getLng()+"";
    //                                return cityInfos;
    //                            }
    //                        }
    //                    }
    //                }
    //            }
    //        }
    //        return null;
    //    }
    
    
        private String[] getJsonToCityInfoAdministrative_area_level_1(String json){
            String[] cityInfos = new String[4];
            GoogleLocationModel googleLocationModel = (GoogleLocationModel) JsonUtil.getInstanceFor().parseObject(json,GoogleLocationModel.class);
            if(googleLocationModel == null){
                return null;
            }else{
                if(googleLocationModel.getStatus().equals("OK")){
                    for (GoogleLocationModel.ResultsBean resultsBean:googleLocationModel.getResults()){
                        for(GoogleLocationModel.ResultsBean.AddressComponentsBean addressComponentsBean:resultsBean.getAddress_components()){
                            for(String type:addressComponentsBean.getTypes()){
                                if(type.equals("administrative_area_level_1")){
                                    cityInfos[0] = addressComponentsBean.getLong_name();
                                    cityInfos[1] = resultsBean.getFormatted_address();
                                    cityInfos[2] = resultsBean.getGeometry().getLocation().getLat()+"";
                                    cityInfos[3] = resultsBean.getGeometry().getLocation().getLng()+"";
                                    return cityInfos;
                                }
                            }
                        }
                    }
                }
            }
            return null;
        }
    
        private String[] getJsonToCityInfoAdministrative_area_level_2(String json){
            String[] cityInfos = new String[4];
            GoogleLocationModel googleLocationModel = (GoogleLocationModel) JsonUtil.getInstanceFor().parseObject(json,GoogleLocationModel.class);
            if(googleLocationModel == null){
                return null;
            }else{
                if(googleLocationModel.getStatus().equals("OK")){
                    for (GoogleLocationModel.ResultsBean resultsBean:googleLocationModel.getResults()){
                        for(GoogleLocationModel.ResultsBean.AddressComponentsBean addressComponentsBean:resultsBean.getAddress_components()){
                            for(String type:addressComponentsBean.getTypes()){
                                if(type.equals("administrative_area_level_2")){
                                    cityInfos[0] = addressComponentsBean.getLong_name();
                                    cityInfos[1] = resultsBean.getFormatted_address();
                                    cityInfos[2] = resultsBean.getGeometry().getLocation().getLat()+"";
                                    cityInfos[3] = resultsBean.getGeometry().getLocation().getLng()+"";
                                    return cityInfos;
                                }else{
                                    getJsonToCityInfoAdministrative_area_level_1(json);
                                    break;
                                }
                            }
                        }
                    }
                }
            }
            return null;
        }
    
        private String[] getJsonToCityInfoLocality(String json){
            String[] cityInfos = new String[4];
            GoogleLocationModel googleLocationModel = (GoogleLocationModel) JsonUtil.getInstanceFor().parseObject(json,GoogleLocationModel.class);
            if(googleLocationModel == null){
                return null;
            }else{
                if(googleLocationModel.getStatus().equals("OK")){
                    for (GoogleLocationModel.ResultsBean resultsBean:googleLocationModel.getResults()){
                        for(GoogleLocationModel.ResultsBean.AddressComponentsBean addressComponentsBean:resultsBean.getAddress_components()){
                            for(String type:addressComponentsBean.getTypes()){
                                if(type.equals("locality")){
                                    cityInfos[0] = addressComponentsBean.getLong_name();
                                    cityInfos[1] = resultsBean.getFormatted_address();
                                    cityInfos[2] = resultsBean.getGeometry().getLocation().getLat()+"";
                                    cityInfos[3] = resultsBean.getGeometry().getLocation().getLng()+"";
                                    return cityInfos;
                                }else{
                                    getJsonToCityInfoAdministrative_area_level_2(json);
                                    break;
                                }
                            }
                        }
                    }
                }
            }
            return null;
        }
    
    
        public interface OnGoogleLocationListener{
            void onGoogleLocationSuccessCallback(String... cityInfo);
            void onGoogleLocationFailCallback(String... errorMsg);
        }
    
        public interface OnGoogleRouleListener{
            void onGoogleRouleSuccessCallback(Object... rouleInfo);
            void onGoogleRouleFailCallback(String... errorMsg);
        }
    }
    
    
    展开全文
  • 获取经纬度一般有两种方法通过集成第三方(百度、高德)来获取通过Android自带的API来获取那么今天我就来写一下第二种通过Android自带的API来获取经纬度的方法:首先经纬度需要用户授权,权限如下第一步 获取...

    获取经纬度一般有两种方法

    通过集成第三方(百度、高德)来获取

    通过Android自带的API来获取

    那么今天我就来写一下第二种通过Android自带的API来获取经纬度的方法:

    首先经纬度需要用户授权,权限如下

    第一步 获取LocationManager对象,代码如下

    // 获取位置服务

    String serviceName = Context.LOCATION_SERVICE;

    // 调用getSystemService()方法来获取LocationManager对象

    locationManager = (LocationManager) getSystemService(serviceName);

    第二步 指定LocationManager的定位方法 ,然后调用LocationManager.getLastKnowLocation()方法获取当前位置 代码如下

    // 指定LocationManager的定位方法

    String provider = LocationManager.GPS_PROVIDER;

    // 调用getLastKnownLocation()方法获取当前的位置信息

    Location location = locationManager.getLastKnownLocation(provider);

    第三步 调用Location中的getLatitude()和getLonggitude()方法可以分别获取位置信息中的纬度和经度,代码如下

    //获取纬度

    double lat = location.getLatitude();

    //获取经度

    double lng = location.getLongitude();

    通常情况下到这里我们已经通过Android自带的API获取到了经纬度,但是有的时候会获取不到,或者我们需要获取连续的点位信息,下面我就来写一下如何获取连续的点位信息,同时我们可以通过这种方式来避免获取点位失败的问题。

    首先我们要调用requestLocationUpdates,代码如下

    locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 3000, 0, mLocationListener01);

    locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 3000, 0, mLocationListener01);

    其中有四个参数

    第一个是定位模式,一般有gps和network两种

    第二个是更新的时间单位毫秒

    第三个是更新的距离单位是米

    第四个是位置服务的监听

    第一步 我们要实现一个LocationListener,代码如下

    mLocationListener01 = new LocationListener() {

    @Override

    public void onProviderDisabled(String provider) {

    updateToNewLocation(null);

    }

    @Override

    public void onProviderEnabled(String provider) {

    }

    @Override

    public void onLocationChanged(Location location) {

    //调用更新位置

    updateToNewLocation(location);

    }

    @Override

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

    }

    };

    我们来看下更新位置函数代码如下

    private Location updateToNewLocation(Location location) {

    String latLongString;

    if (location != null) {

    lat = location.getLatitude();

    lng = location.getLongitude();

    if (locationManager != null) {

    locationManager.removeUpdates(mLocationListener01);

    locationManager = null;

    }

    if (mLocationListener01 != null) {

    mLocationListener01 = null;

    }

    } else {

    Toast.makeText(getApplicationContext(), "无法获取地理信息,请确认已开启定位权限并选择定位模式为GPS、WLAN和移动网络", Toast.LENGTH_SHORT).show();

    }

    return location;

    }

    这样我们就可以获取连续的点位信息了。

    不过获取单个点位的时候我也建议使用这种方法,因为他可以避免Location为空的问题。

    使用起来也很简单,只要我们获取到点位之后就停止继续获取点位就可以了

    停止方法为

    if (locationManager != null) {

    locationManager.removeUpdates(mLocationListener01);

    locationManager = null;

    }

    if (mLocationListener01 != null) {

    mLocationListener01 = null;

    }

    把这段代码加到我们自己写的更新函数里即可,代码如下

    private Location updateToNewLocation(Location location) {

    String latLongString;

    if (location != null) {

    lat = location.getLatitude();

    lng = location.getLongitude();

    if (locationManager != null) {

    locationManager.removeUpdates(mLocationListener01);

    locationManager = null;

    }

    if (mLocationListener01 != null) {

    mLocationListener01 = null;

    }

    } else {

    Toast.makeText(getApplicationContext(), "无法获取地理信息,请确认已开启定位权限并选择定位模式为GPS、WLAN和移动网络", Toast.LENGTH_SHORT).show();

    }

    return location;

    }

    好了,Android获取经纬度就写到这里,以后如果仅仅是获取经纬度的话可以不用集成第三方的东西了,希望对大家有所帮助。

    展开全文
  • android获取经纬度且解析位置,该demo能够通过network和gps获取当前所在的经纬信息,并能实时的更新,并且能通过经纬度信息上传到googleMap上获取相对应的地址信息,返回的事json字符串,最后解析成一般的地址信息。...
  • 通过Android的原生api获取经纬度;一些文章都是通过mLocationManager.getProviders,getLastKnownLocation来获取的,但是在一些手机上总是为空。例如:在一些手机Android 5.0(api21 联想手机)上getLastKnownLocation...

    通过Android的原生api获取经纬度;

    一些文章都是通过mLocationManager.getProviders,getLastKnownLocation来获取的,但是在一些手机上总是为空。

    例如:在一些手机Android 5.0(api21 联想手机)上getLastKnownLocation获取总为空。

    可以通过getBestProvider来获取provider然后通过getLastKnownLocation获取得到经纬度。

    private Location getLastKnownLocation() {

    //获取地理位置管理器

    LocationManager mLocationManager = (LocationManager) getApplicationContext().getSystemService(LOCATION_SERVICE);

    if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED

    && ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {

    // TODO:去请求权限后再获取

    return null;

    }

    List providers = mLocationManager.getProviders(true);

    Location bestLocation = null;

    for (String provider : providers) {

    Location l = mLocationManager.getLastKnownLocation(provider);

    if (l == null) {

    continue;

    }

    if (bestLocation == null || l.getAccuracy() < bestLocation.getAccuracy()) {

    bestLocation = l;

    }

    }

    // 在一些手机5.0(api21)获取为空后,采用下面去兼容获取。

    if (bestLocation==null){

    Criteria criteria = new Criteria();

    criteria.setAccuracy(Criteria.ACCURACY_COARSE);

    criteria.setAltitudeRequired(false);

    criteria.setBearingRequired(false);

    criteria.setCostAllowed(true);

    criteria.setPowerRequirement(Criteria.POWER_LOW);

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

    if (!TextUtils.isEmpty(provider)){

    bestLocation = mLocationManager.getLastKnownLocation(provider);

    }

    }

    return bestLocation;

    }

    // 使用

    Location location = getLastKnownLocation();

    LogUtils.d(TAG, "有位置权限-纬度:" + location.getLatitude() + " 经度:" + location.getLongitude());

    展开全文
  • Android 获取经纬度的服务

    千次阅读 2018-04-13 11:19:52
    Android 获取经纬度的服务 使用原生Android API 编写一个Service类获取经纬度信息(本文仅作为学习笔记来使用,若侵犯到您的权益,请及时与我联系,我会删除涉及侵犯到您的内容)。 一, 实现步骤 添加对应的权限...
  • 获取经纬度 使用GPS权限: 代码如下:<uses android:name=”android.permission.ACCESS_FINE_LOCATION”> Android提供LocationManager和Location,可以方便的获得经纬度、海拔等位置。使用LocationManager来获得位置...
  • 经度指示南北方向,纵向纬度指示东西方向,横向获取经纬度使用GPS权限:Android提供LocationManager和Location,可以方便的获得经纬度、海拔等位置。使用LocationManager来获得位置管理类,从而可以获得历史GPS信息...
  • android 获取经纬度demo

    2013-01-09 19:22:39
    android通过network获取当前的经纬度和地理位置
  • 最近在Android上作GPS的东西,获取经纬度、计算距离、方位角,感受在搞GIS样。固然,玩笑了,玩玩而已,稍微总结一下。html经度指示南北方向,纵向。android纬度指示东西方向,横向.git 获取经纬度使用GPS权限:ide...
  • 这次来总结一下我用到的Android原生获取经纬度和地址信息的案例,喜欢的可以收藏下,不喜勿喷!!! 1、一般来说,既然获取经纬度等信息,就需要获取定位权限啦。 可以在你的首页或者应用启动时先写获取权限的逻辑...
  • 本机位置获取工具类 package com.xinchengle.xiaokedou.utils; import android.annotation.SuppressLint; import android.content.Context; import android.content.pm.PackageManager; import android.location....
  • 经过测试发现,在有的手机上获取经纬度没有问题,在其他的手机上获取经纬度却又问题,因此我查看了谷歌提供的源码,从源码里面提取出了一份新的获取经纬度的代码,以后每次获取基本都获取成功了: ...

空空如也

空空如也

1 2 3 4 5 ... 20
收藏数 10,787
精华内容 4,314
关键字:

安卓获取经纬度