百度地图定位和IP地址定位

来源:互联网 发布:mac 终端退出 bash 编辑:程序博客网 时间:2024/04/30 02:46

百度开放平台:更多配置和lib http://lbsyun.baidu.com/

1.显示基础地图:SDKInitializer.initialize(getApplicationContext()); //在入口文件进行初始化

/**MapView mMapView=(MapView)findViewById(R.id.bmapView);//百度地图 如果fragment布局用com.baidu.mapapi.map.TextureMapView*mMapView.showZoomControls(false);//隐藏缩放按钮  mMapView.showScaleControl(false);//隐藏比例尺*mBaiduMap = mMapView.getMap();*/private void initMap(BaiduMap mBaiduMap,List<Data> mLatLng) {if(mBaiduMap==null||mLatLng==null){return;}//在地图上添加Marker,并显示  ArrayList<OverlayOptions>alOverlay=new ArrayList<OverlayOptions>();ArrayList<LatLng>alLatLng=new ArrayList<LatLng>();LatLng scaleLatLng=null;for(int i=0;i<mLatLng.size();i++){double[] gcj2bd = gcj2bd(mLatLng.get(i).latitude, mLatLng.get(i).longitude);//是否需要地理编码转经纬度//定义Maker坐标点  LatLng pointLatLng = new LatLng(gcj2bd[0], gcj2bd[1]); scaleLatLng=new LatLng(gcj2bd[0]+0.001, gcj2bd[1]+0.001);alLatLng.add(pointLatLng);//构建Marker图标  BitmapDescriptor bitmap = BitmapDescriptorFactory  .fromResource(R.drawable.logo);//fromView(myView)建议用LinearLayout自定义viewOverlayOptions option = new MarkerOptions().position(pointLatLng)//draggable(true)长按图标才能拖拽.icon(bitmap);alOverlay.add(option);}mBaiduMap.addOverlays(alOverlay);//标记打点 //折线构建分段颜色索引数组List<Integer> colors = new ArrayList<Integer>();//colors.add(Integer.valueOf(Color.YELLOW));colors.add(Integer.valueOf(Color.GREEN)); OverlayOptions ooPolyline = new PolylineOptions() .width(10) .colorsValues(colors) .points(alLatLng);mBaiduMap.addOverlay(ooPolyline);//画折线//指定地图显示范围mBaiduMap.setMapStatusLimits(new LatLngBounds.Builder().include(scaleLatLng).include(scaleLatLng).build());//定义地图显示范围        MapStatus mMapStatus = new MapStatus.Builder()        .target(targetLatLng)        .zoom(15f)        .build();        MapStatusUpdate mMapStatusUpdate = MapStatusUpdateFactory.newMapStatus(mMapStatus);        mBaiduMap.setMapStatus(mMapStatusUpdate);        //类型卫星地图  mBaiduMap.setMapType(BaiduMap.MAP_TYPE_SATELLITE);}
public static double[] gcj2bd(double lat, double lon){//http://bbs.lbsyun.baidu.com/forum.php?mod=viewthread&tid=10923&qq-pf-to=pcqq.discussiondouble x_pi = 3.14159265358979324 * 3000.0 / 180.0;double x = lon, y = lat;double z = Math.sqrt(x * x + y * y) + 0.00002 * Math.sin(y * x_pi);double theta = Math.atan2(y, x) + 0.000003 * Math.cos(x * x_pi);double bd_lon = z * Math.cos(theta) + 0.0065;double bd_lat = z * Math.sin(theta) + 0.006;return new double[] { bd_lat, bd_lon };}
2.添加信息弹窗

mBaiduMap.setOnMarkerClickListener(new OnMarkerClickListener() {public boolean onMarkerClick(final Marker marker) {Button button = new Button(getApplicationContext());button.setBackgroundResource(R.drawable.popup);button.setText("更换图标");button.setOnClickListener(new OnClickListener() {public void onClick(View v) {marker.setIcon(bd);mBaiduMap.hideInfoWindow();}});LatLng ll = marker.getPosition();InfoWindow mInfoWindow = new InfoWindow(button, ll, -47);mBaiduMap.showInfoWindow(mInfoWindow);return true;}});

3.GPS定位

public void initLocation(Context context){LocationClient mLocationClient = new LocationClient(context);     //声明LocationClient类mLocationClient.registerLocationListener( new MyLocationListener(context) );    //注册监听函数        LocationClientOption option = new LocationClientOption();        option.setLocationMode(LocationMode.Hight_Accuracy);//可选,默认高精度,设置定位模式,高精度,低功耗,仅设备        option.setCoorType("bd09ll");//可选,默认gcj02,设置返回的定位结果坐标系//        option.setScanSpan(1000);//可选,默认0,即仅定位一次,设置发起定位请求的间隔需要大于等于1000ms才是有效的        option.setIsNeedAddress(true);//可选,设置是否需要地址信息,默认不需要        option.setOpenGps(true);//可选,默认false,设置是否使用gps//        option.setLocationNotify(true);//可选,默认false,设置是否当gps有效时按照1S1次频率输出GPS结果        option.setIsNeedLocationDescribe(true);//可选,默认false,设置是否需要位置语义化结果,可以在BDLocation.getLocationDescribe里得到,结果类似于“在北京天安门附近”        option.setIsNeedLocationPoiList(true);//可选,默认false,设置是否需要POI结果,可以在BDLocation.getPoiList里得到        option.setIgnoreKillProcess(false);//可选,默认true,定位SDK内部是一个SERVICE,并放到了独立进程,设置是否在stop的时候杀死这个进程,默认不杀死          option.SetIgnoreCacheException(false);//可选,默认false,设置是否收集CRASH信息,默认收集        option.setEnableSimulateGps(false);//可选,默认false,设置是否需要过滤gps仿真结果,默认需要                mLocationClient.setLocOption(option);        mLocationClient.start();    }/** * 位置广播bc */private class MyLocationListener implements BDLocationListener {private Context mCon;public MyLocationListener(Context mCon) {this.mCon=mCon;}@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号和大体定位时间到loc-bugs@baidu.com,会有人追查原因");            } 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());                    }                }                mLatitude = location.getLatitude();                mLongitude = location.getLongitude();                mCity= location.getCity();                Log.e("--------------","------------------城市"+mCity);                                       //如果要在地图显示,构造定位数据             mBaiduMap.setMyLocationEnabled(true);                 MyLocationData locData = new MyLocationData.Builder()                 .accuracy(location.getRadius())                .direction(90)//方向信息,顺时针0-360               .latitude(location.getLatitude())               .longitude(location.getLongitude()).build();                 mBaiduMap.setMyLocationData(locData); //设置定位数据  //// 设置定位图层的配置(定位模式,是否允许方向信息,用户自定义定位图标)  //BitmapDescriptor mCurrentMarker = BitmapDescriptorFactory .fromResource(R.drawable.ic_launcher);  //MyLocationConfiguration config = new MyLocationConfiguration(MyLocationConfiguration.LocationMode.NORMAL,true, mCurrentMarker);  //mBaiduMap.setMyLocationConfigeration(config);           }}

4.方向传感器和定位图标方向MyLocationData.direction()

[java] view plain copy
 在CODE上查看代码片派生到我的代码片
  1. public class MyOrientationListener implements SensorEventListener{  
  2.   
  3.     private SensorManager mSensorManager;  
  4.     private Sensor mSensor;  
  5.     private Context mContext;  
  6.     private float lastX;  
  7.     private OnOrientationListener mOnOrientationListener;  
  8.   
  9.     public MyOrientationListener(Context context)  
  10.     {  
  11.         this.mContext=context;  
  12.     }  
  13.     public void start()  
  14.     {  
  15.         mSensorManager= (SensorManager) mContext  
  16.                 .getSystemService(Context.SENSOR_SERVICE);  
  17.         if(mSensorManager!= null)  
  18.         {  
  19.             //获得方向传感器  
  20.             mSensor=mSensorManager.getDefaultSensor(Sensor.TYPE_ORIENTATION);  
  21.         }  
  22.         //判断是否有方向传感器  
  23.         if(mSensor!=null)  
  24.         {  
  25.             //注册监听器  
  26.             mSensorManager.registerListener(this,mSensor,SensorManager.SENSOR_DELAY_UI);  
  27.   
  28.         }  
  29.   
  30.   
  31.     }  
  32.     public void stop()  
  33.     {  
  34.         mSensorManager.unregisterListener(this);  
  35.   
  36.     }  
  37.     //方向改变  
  38.     @Override  
  39.     public void onSensorChanged(SensorEvent event) {  
  40.         if(event.sensor.getType()==Sensor.TYPE_ORIENTATION)  
  41.         {  
  42.             float x=event.values[SensorManager.DATA_X];  
  43.             if(Math.abs(x-lastX)>1.0)  
  44.             {  
  45.                 if(mOnOrientationListener!=null)  
  46.                 {  
  47.                     mOnOrientationListener.onOrientationChanged(x);  
  48.                 }  
  49.             }  
  50.             lastX=x;  
  51.   
  52.         }  
  53.   
  54.     }  
  55.     public void setOnOrientationListener(OnOrientationListener listener)  
  56.     {  
  57.         mOnOrientationListener=listener;  
  58.     }  
  59.   
  60.     public interface OnOrientationListener  
  61.     {  
  62.         void onOrientationChanged(float x);  
  63.   
  64.     }  
  65.   
  66.     @Override  
  67.     public void onAccuracyChanged(Sensor sensor, int accuracy) {  
  68.   
  69.     }  

在mapview类调用百度地图对应方法 mMapView.onPause();mMapView.onResume();mMapView.onDestroy();


更多:修改IP地址

经纬度地址转换:Geocoder geocoder = new Geocoder(this);

两点之间距离:float[] results=new float[1];  
Location.distanceBetween(mlatitude, mlongitude,latitude,longitude, results);

1、IP网络定位方法:http://ip-api.com/json/
import android.provider.Settings;
import android.content.ContentResolver;
ps:在Setting.System中有以下标志
WIFI_USE_STATIC_IP
WIFI_STATIC_IP
WIFI_STATIC_NETMASK
WIFI_STATIC_GATEWAY
WIFI_STATIC_DNS1 and WIFI_STATIC_DNS2
2、在AndroidManifest中加入<uses-permission  android:name="android.permission.WRITE_SETTINGS"/>
3、在Activity中可以这样用:
final ContentResolver mContentResolver = getContentResolver();
Settings.System.putInt( mContentResolver, Settings.System.WIFI_USE_STATIC_IP, 1);
Settings.System.putString( mContentResolver, Settings.System.WIFI_STATIC_IP, "你的ip地址");

http://blog.csdn.net/a704755096/article/details/48467227


1 0
原创粉丝点击