百度定位+精确定位+模糊城市定位

Posted 西域黄老板

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了百度定位+精确定位+模糊城市定位相关的知识,希望对你有一定的参考价值。

百度定位相信大家都会使用,作为一个一年经验的安卓经验的新人,我也就不多说什么了.今天要给大家带来的是一个模糊定位,一个小小的需求,就是根据自己的定位地点的经纬度,解析旁边城市的经纬度,得到一个距离最近的城市.详细的和大家描述一下.
比如点 深圳(x1,y1)–>(地点名称)(纬度,经度)
北京(x2,y2)–>(地点名称)(纬度,经度)
如果我现在的定位地点是广州(x3,y3).
那么广州和深圳的距离是[(x3-x1)(x3-x1)]开方,同理广州和北京的距离是[(x3-x2)(x3-x2)]开方.比较两段距离的长度,判断自己离哪个城市更近,则选择哪个城市.
需求就是这么简单.
这里写图片描述
这里![

一下是源码和包

<MainActivity>

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.GridView;
import android.widget.TextView;
import android.widget.Toast;

import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;

public class MainActivity extends Activity {

    private GridView gridview;
    private List<Map<String, String>>list = new ArrayList<Map<String,String>>();

    private TextView city_tv;

    private String back_city;

    private List<Map<String, String>>list_hz = new ArrayList<Map<String,String>>();

    /******************************************定位代码的实现*************************/
    private String TAG = "MainActivity";
    /** 定位成功标识 */
    private final int LOCATION_SUCCESS = 1;
    /** 定位失败标识 */
    private final int LOCATION_ERROR = 0;
    /** 百度定位器 */
    private LocationClient mLocClient;
    /** 延迟发送,设置成全局,用于解决快速按按钮导致的开启了多个线程 */
    private Runnable mRunable;
    /******************************************定位代码的实现*************************/

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

        back_city = "深圳";

        /******************************************定位代码的实现*************************/
        initData();
        /******************************************定位代码的实现*************************/

        //初始化id
        setViews();

        //设置城市列表属性
        setGridView();

        //设置国家城市经纬度
        setHZ();


        /******************************************定位代码的实现*************************/
        mRunable = new Runnable() {

            @Override
            public void run() {
                mLocClient.start();// 开始定位
            }
        };
        handler.postDelayed(mRunable,0);
        /******************************************定位代码的实现*************************/
        city_tv.setText("正在定位...");

    }

    //初始化城市坐标点数据
    private void setHZ() {
        list_hz = new ArrayList<Map<String,String>>();
        String str[] = {"北京","上海","广州",
                "深圳","杭州","天津",
                "苏州","南京","成都",
                "重庆","西安","武汉",
                "沈阳","宁波","长沙",
                "济南","郑州","无锡",
                "青岛","哈尔滨","温州",
                "福州","香港"};
        String xx[] = {"39.26","30.4","23.11",
                "22.37","30.3","38.33",
                "31.3","32.03","30.67",
                "29.5","34.15","29.58",
                "41.8","28.51","27.51",
                "36.40","34.16","31.7",
                "35.35","44.04","27.03",
                "26.08","22.15"};
        String yy[] = {"115.25","120.51","113.27",
                "114.04","120.2","116.42",
                "120.6","118.46","104.06",
                "106.5","108.56","113.41",
                "123.4","120.55","111.53",
                "117","112.42","119.33",
                "119.30","125.42","119.37",
                "119.28","114.15"};

        for (int i = 0; i < str.length; i++) {
            Map<String, String>map = new HashMap<String, String>();
            map.put("address", str[i]);
            map.put("weidu", xx[i]);
            map.put("jingdu", yy[i]);
            list_hz.add(map);
        }



    }

    /******************************************定位代码的实现*************************/
    private void initData() {
        Log.i("TGA", "===initData()");
        /* 初始化定位信息 */
        mLocClient = new LocationClient(this);// 创建定位器
        // mLocClient.setAK("64qAcRkfBfe6Rh6c37tfEAi8");// 设置Key值
        mLocClient.registerLocationListener(mLocationListener);

        LocationClientOption mLocOption = new LocationClientOption();// 位置区域设置
        mLocOption.setOpenGps(true);// 开启手机GPS导航
        mLocOption.setAddrType("all");// 返回的定位结果包含地址信息
        mLocOption.setCoorType("bd09ll");// 返回的定位结果是百度经纬度,默认值gcj02.必须用这个才能和地图完美匹配。
        mLocOption.setScanSpan(5000);// 设置发起定位请求的间隔时间为5000ms
        mLocOption.disableCache(true);// 禁止启用缓存定位
        mLocOption.setPoiNumber(5); // 最多返回POI个数
        mLocOption.setPoiDistance(1000); // poi查询距离
        mLocOption.setPoiExtraInfo(true); // 是否需要POI的电话和地址等详细信息
        mLocClient.setLocOption(mLocOption);
    }
    /******************************************定位代码的实现*************************/


    //初始化id
    private void setViews() {
        gridview = (GridView) findViewById(R.id.gridview);
        city_tv = (TextView) findViewById(R.id.city_tv);
    }

    //设置城市列表属性
    private void setGridView() {
        String str[] = {"北京","上海","广州","深圳","杭州","天津","苏州","南京","成都","重庆","西安","武汉","沈阳","宁波","长沙","济南","郑州","无锡","青岛","哈尔滨","温州","福州","香港"};
        for (int i = 0; i < str.length; i++) {
            Map<String, String>map = new HashMap<String, String>();
            map.put("1", str[i]);
            list.add(map);
        }

        YesPosition_adapter adapter = new YesPosition_adapter(this, list,back_city);
        gridview.setAdapter(adapter);
        gridview.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
                    long arg3) {
                //返回带参
                /*Intent intent=getIntent();
                intent.putExtra("str", list.get(arg2).get("1"));
                setResult(Activity.RESULT_OK,intent);
                finish();*/

                Toast.makeText(MainActivity.this, list.get(arg2).get("1"), 0).show();

            }
        });

    }

    public void doclick(View v){
        switch (v.getId()) {
        case R.id.back_rl1:
            finish();
            break;
        case R.id.position:
            /*Intent intent=getIntent();
            intent.putExtra("str", city_tv.getText().toString()+"");
            setResult(Activity.RESULT_OK,intent);
            finish();*/

            Toast.makeText(this, city_tv.getText().toString(), 0).show();

            break;
        }
    }


    /******************************************定位代码的实现*************************/
    /** 自定义的定们监听 */
    private BDLocationListener mLocationListener = new BDLocationListener() {

        @Override
        public void onReceiveLocation(BDLocation location) {
            Log.i(TAG, "===onReceiveLocation(),location-->" + location);
            if (location != null) {
                String city = "";
                String address = "";
                city = location.getCity();
                address = location.getAddrStr();
                double dLat = location.getLatitude();
                double dLon = location.getLongitude();

                //黄石       模拟城市1
                /*city = "黄石";
                address = "湖北省黄石市西塞山区八卦嘴枣子山2单元503";
                double dLat = 30.20;
                double dLon = 115.09;*/

                //大冶      模拟城市2
                /*city = "映秀";
                address = "湖北省黄石市西塞山区八卦嘴枣子山2单元503";
                double dLat = 31.01;
                double dLon = 103.36;*/

                Message msg = handler.obtainMessage();
                if (city == null) {
                    msg.what = LOCATION_ERROR;
                    msg.sendToTarget();
                } else {
                    int end = city.indexOf("市");
                    if (end != -1) {
                        city = city.substring(0, end);
                    }
                    end = address.indexOf("市");
                    if (end != -1) {
                        address = address.substring(end + 1, address.length());
                    }

                    // 定位成功
                    Log.i(TAG, "===dLat-->" + dLat);//纬度
                    Log.i(TAG, "===dLon-->" + dLon);//经度
                    Log.i(TAG, "===city-->" + city);
                    Log.i(TAG, "===address-->" + address);
                    Map<String, String> map = new HashMap<String, String>();
                    map.put("dLat", "" + dLat);//
                    map.put("dLon", "" + dLon);
                    map.put("city", city);
                    map.put("address", address);

                    msg.what = LOCATION_SUCCESS;
                    msg.obj = map;
                    msg.sendToTarget();
                }

            } else {
                Message msg = handler.obtainMessage();
                msg.what = LOCATION_ERROR;
                msg.sendToTarget();
            }
            mLocClient.stop();
        }

        @Override
        public void onReceivePoi(BDLocation arg0) {
            Log.i(TAG, "===onReceivePoi(),arg0-->" + arg0);
        }
    };
    /** 定位操作处理 */
    private Handler handler = new Handler() {

        @Override
        public void handleMessage(Message msg) {
            Log.i(TAG, "===handleMessage()");
            switch (msg.what) {
            case LOCATION_SUCCESS:
                Log.i(TAG, "===定位成功");// 成功
                /* 展示内容 */
                Map<String, String> map = (HashMap<String, String>) msg.obj;
                //              textView_main.setText("dLat:" + map.get("dLat") + "\\n" + "dLon:" + map.get("dLon") + "\\n" + "city:" + map.get("city") + "\\n" + "address:" + map.get("address"));
                //              city_tv.setText(map.get("city") + "哈哈市"  + map.get("address"));
                //              city_tv.setText(map.get("city"));


                //判断定位点的城市名称是否与已有的数组的城市名称有相同,相同则取出
                boolean city_boolean = true;
                for (int i = 0; i < list.size(); i++) {
                    if(list.get(i).get("1").equals(map.get("city"))){
                        city_tv.setText(map.get("city"));
                        city_boolean = false;
                    }
                }

                //不同则执行距离判断语句
                if(city_boolean){

                    String weidu = map.get("dLat");//纬度
                    String jingdu = map.get("dLon");//经度

                    String position_ad = "";
                    String weidu_ad = "";
                    String jingdu_ad = "";
                    int juli = 100000;//给默认最大的距离      比这个距离小则去小
                    for (int i = 0; i < list_hz.size(); i++) {
                        int a1 = (int)(Float.parseFloat((list_hz.get(i).get("weidu"))))-(int)(Float.parseFloat(weidu));//x3-x1
                        int a2 = (int)(Float.parseFloat((list_hz.get(i).get("jingdu"))))-(int)(Float.parseFloat(jingdu));//y3-y1

                        if((a1*a1+a2*a2)<juli){//两点的距离小,则取消的值
                            juli = (a1*a1+a2*a2);
                            position_ad = list_hz.get(i).get("address");//取相对应的城市名称
                        }
                    }

                    city_tv.setText(position_ad);

                }

                break;

            case LOCATION_ERROR:
                Log.i(TAG, "===定位失败");// 失败
                city_tv.setText("定位失败");
                break;
            }
        }

    };
    /******************************************定位代码的实现*************************/
}
<Adapter>

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import android.content.Context;
import android.graphics.Color;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.RelativeLayout;
import android.widget.TextView;

public class YesPosition_adapter extends BaseAdapter{

    private Context context;
    private List<Map<String, String>>list= new ArrayList<Map<String,String>>();
    private String str;

    public YesPosition_adapter(Context context, List<Map<String, String>> list,String str) {
        this.context=context;
        this.list=list;
        this.str = str;
    }

    @Override
    public int getCount() {
        return list.size();
    }

    @Override
    public Object getItem(int position) {
        return list.get(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        ViewHolder holder;
        if(convertView==null){
            holder=new ViewHolder();
            convertView=View.inflate(context, R.layout.item_yesposition, null);
            holder.tv1=(TextView) convertView.findViewById(R.id.tv1);
            holder.rl1=(RelativeLayout) convertView.findViewById(R.id.rl1);
            convertView.setTag(holder);

        }else{
            holder=(ViewHolder) convertView.getTag();
        }

        holder.tv1.setText(list.get(position).get("1"));
        if(str.equals(list.get(position).get("1")+"")){
            holder.rl1.setBackgroundColor(Color.rgb(57, 202, 171));
        }else{
            holder.rl1.setBackgroundColor(Color.rgb(255,255,255));
        }

        return convertView;
    }

    class ViewHolder{
        TextView tv1;
        RelativeLayout rl1;
    }

}
两个xml文件


<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:background="#efefef"
    android:layout_height="match_parent" >

    <RelativeLayout 
        android:layout_width="120dp"
        android:layout_height="45dp"
        >

    <RelativeLayout
        android:id="@+id/rl1"
        android:layout_width="120dp"
        android:layout_height="45dp"
        android:layout_marginLeft="9dp"
        android:layout_marginRight="9dp"
        android:layout_marginTop="3dp"
        android:layout_marginBottom="3dp"
        android:background="#ffffff" >

        <TextView
            android:id="@+id/tv1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_centerHorizontal="true"
            android:layout_centerVertical="true"
            android:text="深圳"
            android:textColor="#272636"
            android:textSize="14sp" />

        <TextView 
            android:layout_width="match_parent"
            android:layout_height="0.5dp"
            android:background="#d2d2d2"
            />

        <TextView 
            android:layout_width="match_parent"
            android:layout_height="0.5dp"
            android:background="#d2d2d2"
            android:layout_alignParentBottom="true"
            />

        <TextView 
            android:layout_width="0.5dp"
            android:layout_height="match_parent"
            android:background="#d2d2d2"
            />

        <TextView 
            android:layout_width="0.5dp"
            android:layout_height="match_parent"
            android:background="#d2d2d2"
            android:layout_alignParentRight="true"
            />

    </RelativeLayout>

    </RelativeLayout>

</RelativeLayout>


<xml文件MainActivity>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >

    <RelativeLayout
        android:id="@+id/relativelayout1"
        android:layout_width="match_parent"
        android:layout_height="50dp"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true"
        android:background="#39caab" >

        <RelativeLayout
            android:id="@+id/back_rl1"
            android:onClick="doclick"
            android:layout_width="50dp"
            android:layout_height="50dp"
            android:layout_alignParentLeft="true" >

            <TextView
                android:layout_width="18dp"
                android:layout_height="18dp"
                android:layout_centerHorizontal="true"
                android:layout_centerVertical="true"
                android:background="@drawable/ic_launcher" />
        </RelativeLayout>

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_centerHorizontal="true"
            android:layout_centerVertical="true"
            android:text="出发城市"
            android:textColor="#272636"
            android:textSize="16sp" />
    </RelativeLayout>

    <LinearLayout
        android:id="@+id/linear"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_below="@+id/relativelayout1"
        android:background="#efefef"
        android:orientation="vertical" >

        <RelativeLayout
            android:layout_width="match_parent"
            android:layout_height="36dp" >

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_centerVertical="true"
                android:layout_marginLeft="18dp"
                android:text="距离您最近的城市"
                android:textColor="#646464"
                android:textSize="12sp" />
        </RelativeLayout>

        <RelativeLayout
            android:layout_width="match_parent"
            android:layout_height="50dp" >

            <RelativeLayout
                android:id="@+id/position"
                android:onClick="doclick"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:layout_marginBottom="5dp"
                android:layout_marginLeft="18dp"
                android:layout_marginRight="18dp"
                android:background="#ffffff" >

                <TextView
                    android:id="@+id/city_tv"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_centerVertical="true"
                    android:layout_marginLeft="18dp"
                    android:text="深圳"
                    android:textColor="#272636"
                    android:textSize="14sp" />

                <TextView 
            android:layout_width="match_parent"
            android:layout_height="0.5dp"
            android:background="#d2d2d2"
            />

        <TextView 
            android:layout_width="match_parent"
            android:layout_height="0.5dp"
            android:background="#d2d2d2"
            android:layout_alignParentBottom="true"
            />

        <TextView 
            android:layout_width="0.5dp"
            android:layout_height="match_parent"
            android:background="#d2d2d2"
            />

        <TextView 
            android:layout_width="0.5dp"
            android:layout_height="match_parent"
            android:background="#d2d2d2"
            android:layout_alignParentRight="true"
            />


            </RelativeLayout>
        </RelativeLayout>

        <RelativeLayout
            android:layout_width="match_parent"
            android:layout_height="36dp" >

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_centerVertical="true"
                android:layout_marginLeft="18dp"
                android:text="热门城市"
                android:textColor="#646464"
                android:textSize="12sp" />
        </RelativeLayout>

        <GridView 
            android:id="@+id/gridview"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:background="@null"
            android:scrollbars="@null"
            android:listSelector="@android:color/transparent"
            android:numColumns="3"
            android:layout_marginLeft="9dp"
            android:layout_marginRight="9dp"
            ></GridView>


    </LinearLayout>

</RelativeLayout>

权限

<!-- 百度地图定位功能所需权限 -->
    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" >
    </uses-permission>
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" >
    </uses-permission>
    <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" >
    </uses-permission>
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" >
    </uses-permission>
    <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" />
    <uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS" >
    </uses-permission>
    <uses-permission android:name="android.permission.READ_LOGS" >
    </uses-permission>
    <uses-permission android:name="android.permission.VIBRATE" />
    <uses-permission android:name="android.permission.WAKE_LOCK" />
    <uses-permission android:name="android.permission.WRITE_SETTINGS" />

 <!-- 百度地图定位服务 -->
        <service
            android:name="com.baidu.location.f"
            android:enabled="true"
            android:process=":remote" >
        </service>

以上是关于百度定位+精确定位+模糊城市定位的主要内容,如果未能解决你的问题,请参考以下文章

百度地图API的IP定位城市和浏览器定位(转)

IOS中使用百度地图定位后获取城市坐标,城市名称,城市编号信息

浅谈综合管廊人员精确定位方案

百度地图API 怎么根据输入城市自动定位到该城市中心地点呢

ionic 使用百度地图API, 定位用户当前所在的城市示例

android 版百度地图如何通过定位功能获得当前的位置所在的城市?