安卓定位开发

最近做一个小项目,遇到需要计算当前位置到目标位置的距离,由于项目很小,没有接入百度地图,高德地图,所以要自己写一段代码,现记录如下:

package com.xxxx.xxxx.xxxx.util;

import android.content.Context;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.util.Log;

import java.math.BigDecimal;


public class LocationUtil {

    private static final String TAG = "LocationUtil";

    private static LocationListener locationListener = new LocationListener(){
        @Override
        public void onLocationChanged(Location location) {
            Log.d(TAG, "坐标位置变动了");
            if (location != null) {
                Log.e("Map", "Location changed : Lat: "
                        + location.getLatitude() + " Lng: "
                        + location.getLongitude());
            }
        }

        @Override
        public void onStatusChanged(String s, int i, Bundle bundle) {
            Log.d(TAG, "Provider的状态切换了");
        }

        @Override
        public void onProviderEnabled(String s) {
            Log.d(TAG, "Provider启动了");
        }

        @Override
        public void onProviderDisabled(String s) {
            Log.d(TAG, "Provider关闭了");
        }
    };


    public static String getDistanceWithkilometre(Location currentLoaction, Location huisuoLocation){
        if(currentLoaction!=null && huisuoLocation!=null){
            float distance = huisuoLocation.distanceTo(currentLoaction);
            float kmdistance = distance / 1000;
            BigDecimal b = new BigDecimal(kmdistance);
            kmdistance = b.setScale(2, BigDecimal.ROUND_HALF_UP).floatValue();
            return kmdistance + "公里";
        }else{
            return "无法定位";
        }
    }

    public static Location getCurrentLocation(Context context){
        Location location = null;

        LocationManager locationManager = (LocationManager)context.getSystemService(Context.LOCATION_SERVICE);

        if(locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)){
            location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
            if(location == null){
                location = getCurrentLocationWithWifi(locationManager);
            }
        }else{
            location = getCurrentLocationWithWifi(locationManager);
        }

        return location;
    }

    private static Location getCurrentLocationWithWifi(LocationManager locationManager){
        locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER,1000, 0,locationListener);
        return locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
    }

 getCurrentLocation 用来获取当前的坐标,先用GPS,获取不到的话,用wifi.

 getDistanceWithkilometre 用来获取与目标坐标之间的公里数。

猜你喜欢

转载自squll369.iteye.com/blog/2249909
今日推荐