AS写的百度地图定位demo
版本V6.0.5
先上效果图
demo下载地址:http://download.csdn.net/download/shenyuanqing/9062447
主要步骤
1.获取密钥,需要数字签名(SHA1)跟包名
2.下载相应功能SDK,jar放app/libs文件夹,so文件放app/src/main/jniLibs文件夹并添加依赖
3.根据百度API文档显示Hello BaiduMap
4. 绑定BDLocationListener监听器得到定位经纬度显示在屏幕中间
5.得到屏幕中间点的经纬度进行反向地图编码得到具体地址
6.PoiSearch进行地址搜索
7.正向地图编码即由搜索到的地址转换为经纬度
8.得到经纬度后,就可以显示在屏幕中间了
源码
MainActivity
package com.shen.baidumaptest.activity; import android.content.Intent; import android.os.Bundle; import android.util.Log; import android.view.View; 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; import com.baidu.location.Poi; import com.baidu.mapapi.SDKInitializer; import com.baidu.mapapi.map.BaiduMap; import com.baidu.mapapi.map.BitmapDescriptor; import com.baidu.mapapi.map.BitmapDescriptorFactory; import com.baidu.mapapi.map.MapStatus; import com.baidu.mapapi.map.MapStatusUpdate; import com.baidu.mapapi.map.MapStatusUpdateFactory; import com.baidu.mapapi.map.MapView; import com.baidu.mapapi.map.MyLocationConfiguration; import com.baidu.mapapi.map.MyLocationData; import com.baidu.mapapi.model.LatLng; import com.baidu.mapapi.search.core.SearchResult; import com.baidu.mapapi.search.geocode.GeoCodeResult; import com.baidu.mapapi.search.geocode.GeoCoder; import com.baidu.mapapi.search.geocode.OnGetGeoCoderResultListener; import com.baidu.mapapi.search.geocode.ReverseGeoCodeOption; import com.baidu.mapapi.search.geocode.ReverseGeoCodeResult; import com.shen.baidumaptest.R; import java.util.List; public class MainActivity extends BaseActivity { private MapView mapView=null; private BaiduMap baiduMap; private LocationClient locationClient=null; private BDLocationListener locationListener=new MyLocationListener(); private double latitude,latitudeLocation; private double longitude,longitudeLocation; private String addressLocation; private GeoCoder search=null; private TextView tvAddress,tvCity; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); SDKInitializer.initialize(getApplicationContext()); setContentView(R.layout.activity_main); /**竖屏**/ setOrientationPortrait(); initView(); } private void initView(){ tvAddress=(TextView) findViewById(R.id.tv_address); tvCity=(TextView) findViewById(R.id.tv_city); mapView=(MapView) findViewById(R.id.mapview); baiduMap=mapView.getMap(); locationClient=new LocationClient(getApplicationContext()); locationClient.registerLocationListener(locationListener); initLocation(); locationClient.start(); /**滑屏触发地图状态改变监听器**/ baiduMap.setOnMapStatusChangeListener(new BaiduMap.OnMapStatusChangeListener() { @Override public void onMapStatusChangeStart(MapStatus mapStatus) { } @Override public void onMapStatusChange(MapStatus mapStatus) { } /**屏幕中间的经纬度**/ @Override public void onMapStatusChangeFinish(final MapStatus mapStatus) { latitude = mapStatus.target.latitude; longitude = mapStatus.target.longitude; LatLng ptCenter = new LatLng(latitude, longitude); search.reverseGeoCode(new ReverseGeoCodeOption().location(ptCenter)); } }); search=GeoCoder.newInstance(); /**根据经纬度得到屏幕中心点地址**/ search.setOnGetGeoCodeResultListener(new OnGetGeoCoderResultListener() { @Override public void onGetGeoCodeResult(GeoCodeResult geoCodeResult) { } @Override public void onGetReverseGeoCodeResult(ReverseGeoCodeResult result) { if (result == null || result.error != SearchResult.ERRORNO.NO_ERROR) { Toast.makeText(MainActivity.this, "抱歉,未能找到结果", Toast.LENGTH_LONG).show(); return; } baiduMap.clear(); baiduMap.setMapStatus(MapStatusUpdateFactory.newLatLng(result.getLocation())); addressLocation = result.getAddress(); tvAddress.setText(result.getAddress()); getCity(); } }); /**跳转到搜索地址页面**/ findViewById(R.id.tv_city).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(MainActivity.this, SearchActivity.class); intent.putExtra("city", tvCity.getText().toString()); startActivityForResult(intent, 0); } }); /**返回定位点**/ findViewById(R.id.rl_locating_point).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { location(latitudeLocation,longitudeLocation); } }); } /**经纬度地址动画显示在屏幕中间**/ private void location(double latitude,double longitude){ LatLng ll = new LatLng(latitude, longitude); MapStatusUpdate msu = MapStatusUpdateFactory.newLatLng(ll); baiduMap.animateMapStatus(msu); tvAddress.setText(addressLocation); getCity(); } /**接收异步返回的定位结果**/ public class MyLocationListener implements BDLocationListener{ @Override public void onReceiveLocation(BDLocation location) { //Receive Location StringBuffer sb = new StringBuffer(256); sb.append("time : "); sb.append(location.getTime()); sb.append("\nerror code : "); sb.append(location.getLocType()); sb.append("\nlatitude : "); sb.append(location.getLatitude()); sb.append("\nlontitude : "); sb.append(location.getLongitude()); sb.append("\nradius : "); sb.append(location.getRadius()); if (location.getLocType() == BDLocation.TypeGpsLocation){// GPS定位结果 sb.append("\nspeed : "); sb.append(location.getSpeed());// 单位:公里每小时 sb.append("\nsatellite : "); sb.append(location.getSatelliteNumber()); sb.append("\nheight : "); sb.append(location.getAltitude());// 单位:米 sb.append("\ndirection : "); sb.append(location.getDirection());// 单位度 sb.append("\naddr : "); sb.append(location.getAddrStr()); sb.append("\ndescribe : "); sb.append("gps定位成功"); } else if (location.getLocType() == BDLocation.TypeNetWorkLocation){// 网络定位结果 sb.append("\naddr : "); sb.append(location.getAddrStr()); //运营商信息 sb.append("\noperationers : "); sb.append(location.getOperators()); sb.append("\ndescribe : "); sb.append("网络定位成功"); } else if (location.getLocType() == BDLocation.TypeOffLineLocation) {// 离线定位结果 sb.append("\ndescribe : "); sb.append("离线定位成功,离线定位结果也是有效的"); } else if (location.getLocType() == BDLocation.TypeServerError) { sb.append("\ndescribe : "); sb.append("服务端网络定位失败,可以反馈IMEI号和大体定位时间到[email protected],会有人追查原因"); } else if (location.getLocType() == BDLocation.TypeNetWorkException) { sb.append("\ndescribe : "); sb.append("网络不同导致定位失败,请检查网络是否通畅"); } else if (location.getLocType() == BDLocation.TypeCriteriaException) { sb.append("\ndescribe : "); sb.append("无法获取有效定位依据导致定位失败,一般是由于手机的原因,处于飞行模式下一般会造成这种结果,可以试着重启手机"); } sb.append("\nlocationdescribe : "); sb.append(location.getLocationDescribe());// 位置语义化信息 List<Poi> list = location.getPoiList();// POI数据 if (list != null) { sb.append("\npoilist size = : "); sb.append(list.size()); for (Poi p : list) { sb.append("\npoi= : "); sb.append(p.getId() + " " + p.getName() + " " + p.getRank()); } } Log.e("BaiduLocationApiDem", sb.toString()); showCurrentPosition(location); } } /**配置定位SDK参数**/ private void initLocation(){ LocationClientOption option=new LocationClientOption(); option.setLocationMode(LocationClientOption.LocationMode.Hight_Accuracy); option.setCoorType("bd09ll"); // int span=1000; // option.setScanSpan(span); option.setIsNeedAddress(true); option.setOpenGps(true); option.setLocationNotify(true); option.setIsNeedLocationDescribe(true); option.setIsNeedLocationPoiList(true); option.setIgnoreKillProcess(false); option.setEnableSimulateGps(false); locationClient.setLocOption(option); } /**定位**/ private void showCurrentPosition(BDLocation location){ baiduMap.setMyLocationEnabled(true); MyLocationData locationData=new MyLocationData.Builder() .accuracy(location.getRadius()) .direction(100).latitude(location.getLatitude()) .longitude(location.getLongitude()).build(); // MyLocationConfiguration.LocationMode locationMode=MyLocationConfiguration.LocationMode.NORMAL; // BitmapDescriptor mCurrentMarker = BitmapDescriptorFactory.fromResource(R.mipmap.ic_launcher); // MyLocationConfiguration config = new MyLocationConfiguration(locationMode, true, mCurrentMarker); // baiduMap.setMyLocationConfigeration(config); baiduMap.setMyLocationData(locationData); latitudeLocation=location.getLatitude(); longitudeLocation=location.getLongitude(); addressLocation=location.getAddrStr(); location(latitudeLocation, longitudeLocation); } /**根据搜索页面地名的经纬度定位**/ protected void onActivityResult(int RequestCode,int ResultCode,Intent data){ if(RequestCode==0){ if(ResultCode==1){ location(Double.parseDouble(data.getStringExtra("latitude")),Double.parseDouble(data.getStringExtra("longitude"))); } } } /**得到当前所在城市**/ private void getCity(){ if(addressLocation!=null&&!addressLocation.equals("")){ int indexProvince=addressLocation.indexOf("省"); int indexCity=addressLocation.indexOf("市"); tvCity.setText(addressLocation.substring(indexProvince + 1, indexCity)); } } @Override protected void onResume(){ super.onResume(); mapView.onResume(); } @Override protected void onPause(){ super.onPause(); mapView.onPause(); } @Override protected void onDestroy(){ super.onDestroy(); mapView.onDestroy(); if(locationClient!=null){ locationClient.stop(); } } }SearchActiviy
package com.shen.baidumaptest.activity; import android.content.Intent; import android.os.Bundle; import android.text.Editable; import android.text.TextWatcher; import android.view.View; import android.widget.AdapterView; import android.widget.EditText; import android.widget.ListView; import com.baidu.mapapi.search.core.PoiInfo; import com.baidu.mapapi.search.geocode.GeoCodeOption; import com.baidu.mapapi.search.geocode.GeoCodeResult; import com.baidu.mapapi.search.geocode.GeoCoder; import com.baidu.mapapi.search.geocode.OnGetGeoCoderResultListener; import com.baidu.mapapi.search.geocode.ReverseGeoCodeResult; import com.baidu.mapapi.search.poi.OnGetPoiSearchResultListener; import com.baidu.mapapi.search.poi.PoiCitySearchOption; import com.baidu.mapapi.search.poi.PoiDetailResult; import com.baidu.mapapi.search.poi.PoiResult; import com.baidu.mapapi.search.poi.PoiSearch; import com.shen.baidumaptest.R; import com.shen.baidumaptest.adapter.SearchAdapter; import java.util.ArrayList; import java.util.List; public class SearchActivity extends BaseActivity { private EditText etSearch; private PoiSearch poiSearch; private List<PoiInfo> poiInfo; private SearchAdapter adapter; private GeoCoder search=null; private String city; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_address); goBack(); setOrientationPortrait(); initView(); } private void initView(){ city=getIntent().getStringExtra("city"); poiSearch=PoiSearch.newInstance(); poiInfo=new ArrayList<>(); adapter=new SearchAdapter(this,poiInfo); ListView listView=(ListView) findViewById(R.id.listview); listView.setAdapter(adapter); listView.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { //根据所在城市的地址转换为经纬度 search.geocode(new GeoCodeOption().city(city).address(poiInfo.get(position).address)); } }); search=GeoCoder.newInstance(); /**得到经纬度**/ search.setOnGetGeoCodeResultListener(new OnGetGeoCoderResultListener() { @Override public void onGetGeoCodeResult(GeoCodeResult geoCodeResult) { if (geoCodeResult.getLocation() != null) { Intent intent = new Intent(); intent.putExtra("latitude", geoCodeResult.getLocation().latitude + ""); intent.putExtra("longitude", geoCodeResult.getLocation().longitude + ""); setResult(1, intent); SearchActivity.this.finish(); } } @Override public void onGetReverseGeoCodeResult(ReverseGeoCodeResult reverseGeoCodeResult) { } }); etSearch=(EditText) findViewById(R.id.et_search); etSearch.setText(""); /**刷新查询数据**/ etSearch.addTextChangedListener(new TextWatcher() { @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { } @Override public void onTextChanged(CharSequence s, int start, int before, int count) { } @Override public void afterTextChanged(Editable s) { initData(etSearch.getText().toString()); } }); } private void initData(String key){ OnGetPoiSearchResultListener poiSearchResultListener=new OnGetPoiSearchResultListener() { @Override public void onGetPoiResult(PoiResult poiResult) { poiInfo.clear(); if(poiResult.getAllPoi()!=null){ poiInfo.addAll(poiResult.getAllPoi()); adapter.notifyDataSetChanged(); }else{ adapter.notifyDataSetChanged(); } } @Override public void onGetPoiDetailResult(PoiDetailResult poiDetailResult) { } }; poiSearch.setOnGetPoiSearchResultListener(poiSearchResultListener); poiSearch.searchInCity((new PoiCitySearchOption()) .city(city) .keyword(key)); } private void goBack(){ findViewById(R.id.iv_Back).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { SearchActivity.this.finish(); } }); } }