百度定位相信大家都会使用,作为一个一年经验的安卓经验的新人,我也就不多说什么了.今天要给大家带来的是一个模糊定位,一个小小的需求,就是根据自己的定位地点的经纬度,解析旁边城市的经纬度,得到一个距离最近的城市.详细的和大家描述一下.
比如点 深圳(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;/******************************************定位代码的实现*************************/@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);back_city = "深圳";/******************************************定位代码的实现*************************/initData();/******************************************定位代码的实现*************************///初始化idsetViews();//设置城市列表属性setGridView();//设置国家城市经纬度setHZ();/******************************************定位代码的实现*************************/mRunable = new Runnable() {@Overridepublic 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);// 设置发起定位请求的间隔时间为5000msmLocOption.disableCache(true);// 禁止启用缓存定位mLocOption.setPoiNumber(5); // 最多返回POI个数mLocOption.setPoiDistance(1000); // poi查询距离mLocOption.setPoiExtraInfo(true); // 是否需要POI的电话和地址等详细信息mLocClient.setLocOption(mLocOption);}/******************************************定位代码的实现*************************///初始化idprivate 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() {@Overridepublic 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() {@Overridepublic 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();}@Overridepublic void onReceivePoi(BDLocation arg0) {Log.i(TAG, "===onReceivePoi(),arg0-->" + arg0);}};/** 定位操作处理 */private Handler handler = new Handler() {@Overridepublic 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-x1int a2 = (int)(Float.parseFloat((list_hz.get(i).get("jingdu"))))-(int)(Float.parseFloat(jingdu));//y3-y1if((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;}@Overridepublic int getCount() {return list.size();}@Overridepublic Object getItem(int position) {return list.get(position);}@Overridepublic long getItemId(int position) {return position;}@Overridepublic 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>

百度定位+精确定位+模糊城市定位相关推荐

  1. 微信小程序开发之城市定位

    背景: 在进行小程序开发时,有一个定位城市的需求,下面就来讲讲怎么实现这个功能的吧 解决方案: 小程序的wx.getLocation()获得是经纬度并不包含地名,所以要通过经纬度用相应的地图转换出地名 ...

  2. GPS全球定位技术、GSM网络定位技术、CDMA网络定位技术精度及其原理介绍

    GPS全球定位技术.GSM网络定位技术.CDMA网络定位技术精度及其原理介绍 1.GPS全球定位技术 GPS全球定位技术(Global Positioning System)是美国从本世纪70年代开始 ...

  3. Vue实现城市定位(利用百度地图)

    在网上观看了大多数实现城市定位的方法,发现大部分都不能实现或者不够详细 以下是整理出实现的方法 1.申请你自己的密钥 百度地图开放平台 | 百度地图API SDK | 地图开发 登录成功后到控制台 这 ...

  4. layui+腾讯地图坐标点选取插件,支持地址关键字模糊/联想搜索、当前城市定位、地址地图标点联动

    插件地址: TMap: layui+腾讯地图坐标点选取插件,支持地址关键字模糊/联想搜索.当前城市定位.地址地图标点联动 实际项目中的案例图: html部分: <div class=" ...

  5. 利用百度地图API进行根据ip定位城市

    根据ip进行定位城市,本次利用的是根据百度地图API进行定位.网上也有其他的方法.本次就将我自己写的东西总结一下: 一.首先获取ip地址 public static String getReqIp(H ...

  6. ios 百度地图指定区域_ios百度地图的使用(普通定位、反地理编码)

    iOS定位 - 普通定位(没有地图) - 反地理编码(得到具体位置),下面通过代码给大家详解,代码如下: #import 使用到的头文件 要引入CoreLocation这个包 使用的代理名称 //1. ...

  7. Android 百度地图开发(二)--- 定位功能之MyLocationOverlay,PopupOverlay的使用

    转载请注明出处http://blog.csdn.net/xiaanming/article/details/11380619 这一篇文章主要讲解的是百度地图的定位功能,然后还有MyLocationOv ...

  8. 滁州市化工厂人员定位系统——苏州新导智能科技,技术精湛,定位精确

    ​ 一.项目概述 当前在滁州的生产基地主要承载了集团家电生产制造的核心功能,人员管理.产线工具如循环车.物料箱等除主要还是依靠传统的人员进行现场管理的方式,这种方式不但需要监管人员亲临现场,而且并不能 ...

  9. 百度地图实现公司位置的定位,可拖动修改公司位置。

    百度地图实现公司位置的定位,可拖动修改公司位置.只需要维护x轴和Y轴的数据到数据库就可以了 可拖动,可搜索. <html><head><script src=" ...

最新文章

  1. [POJ 1442]Black Box
  2. 99%学习前端开发都会遇到的问题,百分之百都没绝对意识
  3. 腾讯基于预训练模型的文本内容理解实践
  4. MongoDB在windows下安装和配置
  5. java byte转十六进制_Python 十六进制hexbytesstr之间的转换和Bcc码的生成
  6. [转]WiX v3.7——支持MSBuild、自更新及引用计数
  7. 中国单箱梁体最宽矮塔斜拉桥合龙
  8. 实践项目:图书馆管理系统
  9. linux系统鼠标主题下载,Ubuntu Linux鼠标主题:bCircle
  10. 物联网:Android端控制ZigBee实现生产环境自动控制
  11. assimp android build,Android assimp编译及引用
  12. html空白键,空格键符号是什么?HTML中空格键符号有哪些?
  13. 实验三 图像空间域平滑与锐化(Python实现)
  14. ORA-28547 连接服务器失败
  15. Android 9.0 蓝牙通讯录 BluetoothPbapClient
  16. 深入学习VMware vSphere---基础知识
  17. ArrayList集合(Java)
  18. (转)对冲基金:AQR合伙人:“沉闷”股票回报更好
  19. Nos项目 ChannelInfo添加SKIP和FAV的图标
  20. Tensorflow下用自己的数据集对Faster RCNN进行训练和测试(二)1

热门文章

  1. 计算几何----极角排序
  2. Linux入门教程——VI/VIM 编辑器
  3. 制作深度WinPE+老毛桃WinPE+Ubuntu启动优盘
  4. AutoJs学习-堆堆乐自动
  5. 怎么把html做成chm,如何使用Doxygen和HTML帮助编译器生成CHM?
  6. 【温故知新系列】软件测试原则的7个基本原则
  7. LaTeX竖立公式符号
  8. centos8 + kubernetes 1.24 master/node 节点
  9. 计算机的配置信息储存在哪里,电脑系统配置在哪里
  10. 综合训练3 计算1~20的阶乘的倒数之和