android studio高德地图的显示于定位(附带逆地理编码围栏)
首先注册高德成为开发者(打开高德地图,点击底部的开发者平台),创建应用,按照要求填写相应信息
网站:http://lbs.amap.com/api/android-sdk/guide/create-project/get-key
途中包含了发布版的SHA1安全码和测试版SHA1安全码,两者的值可以看
照做就一定会获取的。
这里我讲发布版和调试版都用的relase版本的sha1
之后再去下载相应的Jar包,这里我用的是
3D地图的jar包
注意:2D地图的jar包,与3D地图的jar包因为接口有一样的,导致冲突无法使用。
在jnilibs下放入一下文件
因为有些人的android studio无法显示,但又不报错(我就这样)。你就需要将以上红圈类容放入libs,才能显示
之后在
将导入的jar包添加到类包;
选择,找到于自己名字一样的Jar,添加就可以了。之后检查在build.gradle 是否添加了以下类容
compile files('libs/AMap3DMap_5.1.0_AMapSearch_5.1.0_AMapLocation_3.4.0_20170518.jar')
compile 'com.android.support:appcompat-v7:24.2.1'
compile 'com.android.support.constraint:constraint-layout:1.0.2'
testCompile 'junit:junit:4.12'
并且设置jar包的位置为libs
dependencies {
compile fileTree(include: ['*.jar'], dir: 'libs')
androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
exclude group: 'com.android.support', module: 'support-annotations'
})
在androidManifest.xml中添加自己的添加权限
<!-- 用于进行网络定位 -->
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<!-- 用于访问GPS定位 -->
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<!-- 用于获取运营商信息,用于支持提供运营商信息相关的接口 -->
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<!-- 用于访问wifi网络信息,wifi信息会用于进行网络定位 -->
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<!-- 用于获取wifi的获取权限,wifi信息会用来进行网络定位 -->
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE" />
<!-- 用于访问网络,网络定位需要上网 -->
<uses-permission android:name="android.permission.INTERNET" />
<!-- 用于读取手机当前的状态 -->
<uses-permission android:name="android.permission.READ_PHONE_STATE" />
<!-- 用于写入缓存数据到扩展存储卡 -->
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<!-- 用于申请调用A-GPS模块 -->
<uses-permission android:name="android.permission.ACCESS_LOCATION_EXTRA_COMMANDS" />
<!-- 用于申请获取蓝牙信息进行室内定位 -->
<uses-permission android:name="android.permission.BLUETOOTH" />
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />
添加自己的key
<meta-data
android:name="com.amap.api.v2.apikey"
android:value="你的key" />
添加定位方法
<service android:name="com.amap.api.location.APSService" />
在Activity_main.xml中添加
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/text1"/>
<com.amap.api.maps.MapView
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:id="@+id/map">
</com.amap.api.maps.MapView>
在MainActivty的主代码
public class MainActivity extends AppCompatActivity implements AMapLocationListener,GeocodeSearch.OnGeocodeSearchListener { private Button button;
private AMapLocationClient locationClient = null;
private AMapLocationClientOption locationOption = null;
private TextView textView;
private String[] strMsg;
private com.amap.api.maps.AMap aMap;
private MapView mapView;
private GeocodeSearch geocoderSearch;
private Marker geoMarker;
private static LatLonPoint latLonPoint; @Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView = (TextView)findViewById(R.id.text1);
textView = (TextView)findViewById(R.id.textView2);
button=(Button)findViewById(R.id.button);
mapView = (MapView) findViewById(R.id.map);
mapView.onCreate(savedInstanceState);// 此方法必须重写
Location();
final Intent intent=new Intent();
intent.setAction("Utils");
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Bundle data =new Bundle();
data.putString("msg","签到成功");
intent.putExtra("data",data);
sendBroadcast(intent); }
});
} private void initMap(){ if (aMap == null) {
aMap = mapView.getMap(); //用高德默认图标
geoMarker= aMap.addMarker(new MarkerOptions().anchor(0.5f, 0.5f).icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_BLUE)));
//自定义图标
//geoMarker = aMap.addMarker(new MarkerOptions().anchor(0.5f, 0.5f)
// .icon(BitmapDescriptorFactory.fromBitmap(BitmapFactory.decodeResource(getResources(), R.mipmap.punch_dw))));
}
geocoderSearch = new GeocodeSearch(this);
geocoderSearch.setOnGeocodeSearchListener(this);
getAddress(latLonPoint);
} @Override
public void onLocationChanged(AMapLocation loc) {
if (null != loc) {
Message msg = mHandler.obtainMessage();
msg.obj = loc;
msg.what = Utils.MSG_LOCATION_FINISH;
mHandler.sendMessage(msg);
} } Handler mHandler = new Handler() {
public void dispatchMessage(android.os.Message msg) {
switch (msg.what) {
//定位完成
case Utils.MSG_LOCATION_FINISH:
String result = "";
try {
AMapLocation loc = (AMapLocation) msg.obj;
result = Utils.getLocationStr(loc, 1);
strMsg = result.split(",");
Toast.makeText(MainActivity.this, "定位成功", Toast.LENGTH_LONG).show();
textView.setText("地址:" + strMsg[0] + "\n" + "经 度:" + strMsg[1] + "\n" + "纬 度:" + strMsg[2]+"\n");
latLonPoint= new LatLonPoint(Double.valueOf(strMsg[2]), Double.valueOf(strMsg[1]));
initMap();
} catch (Exception e) {
Toast.makeText(MainActivity.this, "定位失败", Toast.LENGTH_LONG).show();
}
break;
default:
break;
}
}; }; public void Location() {
// TODO Auto-generated method stub
try {
locationClient = new AMapLocationClient(this);
locationOption = new AMapLocationClientOption();
// 设置定位模式为低功耗模式
locationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);
// 设置定位监听
locationClient.setLocationListener(this);
locationOption.setOnceLocation(true);//设置为单次定位
locationClient.setLocationOption(locationOption);// 设置定位参数
// 启动定位
locationClient.startLocation();
mHandler.sendEmptyMessage(Utils.MSG_LOCATION_START);
} catch (Exception e) {
Toast.makeText(MainActivity.this, "定位失败", Toast.LENGTH_LONG).show();
}
} /**
* 响应逆地理编码围栏
*/
public void getAddress(final LatLonPoint latLonPoint) {
RegeocodeQuery query = new RegeocodeQuery(latLonPoint, 100,
GeocodeSearch.AMAP);// 第一个参数表示一个Latlng,第二参数表示范围多少米,第三个参数表示是网络 坐标系还是GPS原生坐标系
geocoderSearch.getFromLocationAsyn(query);// 设置同步逆地理编码请求
} /**
* 地理编码查询回调
*/
@Override
public void onGeocodeSearched(GeocodeResult result, int rCode) { } /**
* 逆地理编码回调
*/
@Override
public void onRegeocodeSearched(RegeocodeResult result, int rCode) {
if (rCode == 1000) {
if (result != null && result.getRegeocodeAddress() != null
&& result.getRegeocodeAddress().getFormatAddress() != null) { Toast.makeText(MainActivity.this,result.getRegeocodeAddress().getFormatAddress()
+ "附近",Toast.LENGTH_LONG).show();
aMap.animateCamera(CameraUpdateFactory.newLatLngZoom(
AMapUtil.convertToLatLng(latLonPoint), 15));
geoMarker.setPosition(AMapUtil.convertToLatLng(latLonPoint));
} else { }
} else {
}
} @Override
public void onResume() {
super.onResume();
mapView.onResume();
} /**
* 方法必须重写
*/
@Override
public void onPause() {
super.onPause();
mapView.onPause();
} @Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
mapView.onSaveInstanceState(outState);
} @Override
public void onDestroy() {
super.onDestroy();
mapView.onDestroy();
}
}
在同级的文件下建立自己的类方法,调用到主代码中
AMapUtil代码为:
public class AMapUtil {
/**
* 判断edittext是否null
*/
public static String checkEditText(EditText editText) {
if (editText != null && editText.getText() != null
&& !(editText.getText().toString().trim().equals(""))) {
return editText.getText().toString().trim();
} else {
return "";
}
} public static Spanned stringToSpan(String src) {
return src == null ? null : Html.fromHtml(src.replace("\n", "<br />"));
} public static String colorFont(String src, String color) {
StringBuffer strBuf = new StringBuffer(); strBuf.append("<font color=").append(color).append(">").append(src)
.append("</font>");
return strBuf.toString();
} public static String makeHtmlNewLine() {
return "<br />";
} public static String makeHtmlSpace(int number) {
final String space = " ";
StringBuilder result = new StringBuilder();
for (int i = 0; i < number; i++) {
result.append(space);
}
return result.toString();
} public static String getFriendlyLength(int lenMeter) {
if (lenMeter > 10000) // 10 km
{
int dis = lenMeter / 1000;
return dis + "";
} if (lenMeter > 1000) {
float dis = (float) lenMeter / 1000;
DecimalFormat fnum = new DecimalFormat("##0.0");
String dstr = fnum.format(dis);
return dstr;
} if (lenMeter > 100) {
int dis = lenMeter / 50 * 50;
return dis + "";
} int dis = lenMeter / 10 * 10;
if (dis == 0) {
dis = 10;
} return dis + "";
} public static boolean IsEmptyOrNullString(String s) {
return (s == null) || (s.trim().length() == 0);
} /**
* 把LatLng对象转化为LatLonPoint对象
*/
public static LatLonPoint convertToLatLonPoint(LatLng latlon) {
return new LatLonPoint(latlon.latitude, latlon.longitude);
} /**
* 把LatLonPoint对象转化为LatLon对象
*/
public static LatLng convertToLatLng(LatLonPoint latLonPoint) {
return new LatLng(latLonPoint.getLatitude(), latLonPoint.getLongitude());
} /**
* 把集合体的LatLonPoint转化为集合体的LatLng
*/
public static ArrayList<LatLng> convertArrList(List<LatLonPoint> shapes) {
ArrayList<LatLng> lineShapes = new ArrayList<LatLng>();
for (LatLonPoint point : shapes) {
LatLng latLngTemp = AMapUtil.convertToLatLng(point);
lineShapes.add(latLngTemp);
}
return lineShapes;
} /**
* long类型时间格式化
*/
public static String convertToTime(long time) {
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date date = new Date(time);
return df.format(date);
} public static final String HtmlBlack = "#000000";
public static final String HtmlGray = "#808080"; public static String getFriendlyTime(int second) {
if (second > 3600) {
int hour = second / 3600;
int miniate = (second % 3600) / 60;
return hour + "小时" + miniate + "分钟";
}
if (second >= 60) {
int miniate = second / 60;
return miniate + "分钟";
}
return second + "秒";
} public static String getBusPathTitle(BusPath busPath) {
if (busPath == null) {
return String.valueOf("");
}
List<BusStep> busSetps = busPath.getSteps();
if (busSetps == null) {
return String.valueOf("");
}
StringBuffer sb = new StringBuffer();
for (BusStep busStep : busSetps) {
if (busStep.getBusLines().size() > 0) {
RouteBusLineItem busline = busStep.getBusLines().get(0);
if (busline == null) {
continue;
}
String buslineName = getSimpleBusLineName(busline.getBusLineName());
sb.append(buslineName);
sb.append(" > ");
}
if (busStep.getRailway() != null) {
RouteRailwayItem railway = busStep.getRailway();
sb.append(railway.getTrip() + "(" + railway.getDeparturestop().getName()
+ " - " + railway.getArrivalstop().getName() + ")");
sb.append(" > ");
}
}
return sb.substring(0, sb.length() - 3);
} public static String getBusPathDes(BusPath busPath) {
if (busPath == null) {
return String.valueOf("");
}
long second = busPath.getDuration();
String time = getFriendlyTime((int) second);
float subDistance = busPath.getDistance();
String subDis = getFriendlyLength((int) subDistance);
float walkDistance = busPath.getWalkDistance();
String walkDis = getFriendlyLength((int) walkDistance);
return String.valueOf(time + " | " + subDis + " | 步行" + walkDis);
} public static String getSimpleBusLineName(String busLineName) {
if (busLineName == null) {
return String.valueOf("");
}
return busLineName.replaceAll("\\(.*?\\)", "");
} }
Utils的主代码为:
public class Utils { /**
* 开始定位
*/
public final static int MSG_LOCATION_START = 0;
/**
* 定位完成
*/
public final static int MSG_LOCATION_FINISH = 1;
/**
* 停止定位
*/ /**
* 根据定位结果返回定位信息的字符串
*
* @return
*/
public synchronized static String getLocationStr(AMapLocation location, final int index) {
if (null == location) {
return null;
}
StringBuffer sb = new StringBuffer();
//errCode等于0代表定位成功,其他的为定位失败,具体的可以参照官网定位错误码说明
if (location.getErrorCode() == 0) {
sb.append("定位成功" + "\n");
sb.append("定位类型: " + location.getLocationType() + "\n");
sb.append("经 度 : " + location.getLongitude() + "\n");
sb.append("纬 度 : " + location.getLatitude() + "\n");
sb.append("精 度 : " + location.getAccuracy() + "米" + "\n");
sb.append("提供者 : " + location.getProvider() + "\n"); if (location.getProvider().equalsIgnoreCase(
android.location.LocationManager.GPS_PROVIDER)) {
// 以下信息只有提供者是GPS时才会有
sb.append("速 度 : " + location.getSpeed() + "米/秒" + "\n");
sb.append("角 度 : " + location.getBearing() + "\n");
// 获取当前提供定位服务的卫星个数
sb.append("星 数 : "
+ location.getSatellites() + "\n");
} else {
// 提供者是GPS时是没有以下信息的
sb.append("国 家 : " + location.getCountry() + "\n");
sb.append("省 : " + location.getProvince() + "\n");
sb.append("市 : " + location.getCity() + "\n");
sb.append("城市编码 : " + location.getCityCode() + "\n");
sb.append("区 : " + location.getDistrict() + "\n");
sb.append("区域 码 : " + location.getAdCode() + "\n");
sb.append("地 址 : " + location.getAddress() + "\n");
sb.append("兴趣点 : " + location.getPoiName() + "\n");
return (location.getAddress() + "," + location.getLongitude() + "," + location.getLatitude());
}
//这个方法可以进行反向的地理围栏圈定
//if(location.getLatitude()==“纬度”||location.getLongitude()==“经度”){
// sb.append("可以签到"+"\n");
// return sb.toString(); // }
// else {
// sb.append("不可签到"+"\n"); // } // } else {
//定位失败
sb.append("定位失败" + "\n");
sb.append("错误码:" + location.getErrorCode() + "\n");
sb.append("错误信息:" + location.getErrorInfo() + "\n");
sb.append("错误描述:" + location.getLocationDetail() + "\n");
return sb.toString();
}
return sb.toString(); } }
如果要使用那个逆地理的编码围栏,你需要自己设定button控件的响应事件,通过返回值来控制button是否开启
android studio高德地图的显示于定位(附带逆地理编码围栏)的更多相关文章
- Android编程 高德地图 中如何重写 定位按键 的触发事件 (com.amap.api.maps2d.LocationSource)点击定位后不仅定位在地图中心点上而且可以设置地图的缩放大小和提示
在利用高德地图来编写自己的APP的时候,发现了一种对定位按键的重写方法,那就是利用 com.amap.api.maps2d.LocationSource 接口来重写. 什么是定位按键呢,下图中右 ...
- Android studio 百度地图开发(2)地图定位
Android studio 百度地图开发(2)地图定位 email:chentravelling@163.com 开发环境:win7 64位,Android Studio,请注意是Android S ...
- Android studio 百度地图开发(3)地图导航
Android studio 百度地图开发(3)地图导航 email:chentravelling@163.com 开发环境:win7 64位,Android Studio,请注意是Android S ...
- IOS高德地图逆地理编码定位+网络判断
先说下这功能的流程, 流程:判断用户是否联网--->获取用户地理位置经纬度--->通过经纬度去查询地理位置名称 //高德地图 @property (nonatomic, strong) ...
- Android studio百度地图demo出现230错误,key校验失败
转自daoxiaomianzi原文 Android studio 百度地图demo出现230错误,key校验失败 使用AndroidStudio导入Baidu地图的as版的demo,引入后,发现没有k ...
- 【高德地图API】地理编码与逆地理编码
一.地理编码 该功能实现地理编码服务,即地址匹配,从已知的地址描述到对应的经纬度坐标的转换,即根据地址信息,查询该地址所对应的点坐标等,地址(address) 为必选项,城市(city)为可选项. & ...
- 微信小程序地图之逆地理编码
首先说一下,我微信自带map的api中并没有相关接口可调用.文中的方法建立于高德地图.(顺便吐槽,微信开发文档相比支付宝家的显得好烂!) 最近做项目用到地图定位相关的需求,为了搞定需求看了下相关的文档 ...
- Android 编程 高德地图 (实现显示地图以及定位功能)
本文参考文章: http://www.apkbus.com/blog-904057-63610.html 本人实现的 定位代码:(具体配置省略,可见参考文章) package com.example. ...
- Android 打开高德地图、百度地图进行导航;打开第三方App去导航;
抽成工具类了,复制下来就能直接用了,直接看代码吧: 高德地图Url Api: http://lbs.amap.com/api/amap-mobile/guide/android/navigation ...
随机推荐
- CodeForces 580B(尺取法)
Kefa and Company 题意:Kefa这个人要去吃饭,他要邀请一些朋友一起去,他的每个朋友有两个属性金钱和关系度,要求邀请的人里边任意两个人之间的金钱差的绝对值不大于d:求被邀请的所有朋友的 ...
- java的四舍五入及取整
四舍五入用 Math.round(double a): 向上取整用 Math.ceil(double a): 向下取整用 Math.floor(double a):
- 48.cartinality的基本用法
主要知识点 cartinality的用法 es去重用的是cartinality metric算法,对每个bucket中的指定的field进行去重,然后获取去重后的count,类似于count( ...
- vue 使用插件
上传加载 :vue-infinite-loading
- CODEVS1281 Xn数列 (矩阵乘法+快速乘)
真是道坑题,数据范围如此大. 首先构造矩阵 [ f[0] , 1] * [ a,0 ] ^n= [ f[n],1 ] [ c,1 ] 注意到m, a, c, x0, n, g<=10^18,所以 ...
- 开启mysql远程连接
mysql默认只允许本地连接,也就是说,在安装完mysql后会存在两个root账户,他们的host分别是localhost和127.0.0.1 use mysql; update user set h ...
- [bzoj1812][IOI2006]riv_多叉树转二叉树_树形dp
riv bzoj-1812 IOI-2006 题目大意:给定一棵n个点树,要求在上面建立k个收集站.点有点权,边有边权,整棵树的代价是每个点的点权乘以它和它的最近的祖先收集站的距离积的和. 注释:$1 ...
- Monitor和Lock以及区别
1.Monitor.Enter(object)方法是获取锁,Monitor.Exit(object)方法是释放锁,这就是Monitor最常用的两个方法,当然在使用过程中为了避免获取锁之后因为异常,致锁 ...
- Spring MVC-视图解析器(View Resolverr)-内部资源视图解析器(Internal Resource View Resolver)示例(转载实践)
以下内容翻译自:https://www.tutorialspoint.com/springmvc/springmvc_internalresourceviewresolver.htm 说明:示例基于S ...
- [CSS3] Use Sticky Positioning for Section Headers
We can take advantage of sticky positioning to keep a section header at the top of the page while th ...