手机端GSP地图的定位 并且在网页上显示地图的轨迹

百度地图定位手机端功能开发:

第一步:申请百度的开发者密钥http://developer.baidu.com/map/android-mobile-apply-key.htm 申请到开发API的key.

第二步:依照官方文档在manifest.xml中配置http://openapi.baidu.com/map/geosdk-android-developv2.4.htm

百度地图使用服务:

<service android:name="com.baidu.location.f" android:enabled="true" android:process=":remote" android:permission="android.permission.BAIDU_LOCATION_SERVICE"/>

及联网及使用声明权限:

  1. <permission android:name="android.permission.BAIDU_LOCATION_SERVICE"></permission>
  2. <uses-permission android:name="android.permission.BAIDU_LOCATION_SERVICE"></uses-permission>
第三步:写获取地理位置的类:

import java.util.Date;

 

import com.baidu.location.*;

import com.baidu.mapapi.BMapManager;

import com.baidu.mapapi.MKEvent;

import com.baidu.mapapi.MKGeneralListener;

importcom.mypatroller.data.LocationInfo.SItude;

 

import android.app.Application;

import android.util.Log;

import android.widget.TextView;

import android.widget.Toast;

import android.os.Process;

import android.os.Vibrator;

 

public class Location extends Application {

 

         public  LocationClient mLocationClient = null;

         public  String locationData = "";

         public  String poiData = "";

         publicboolean isGpsOn = true;

         publicMyLocationListenner myListener = new MyLocationListenner();

         publicNotifyLister mNotifyer=null;

         publicVibrator mVibrator01;

        

         publicstatic  SItude slocation = new  SItude(); // 一个包括经纬度的类,包括:latitude,longitude

 

                   //start加入百度题图 路径查询功能

         staticLocation mLocation ;

         //百度MapAPI的管理类

         publicBMapManager mBMapMan = null;

         publicString mStrKey = "A60CECF1348D23466699D42836FC436FC151E0AC";//百度地图调用KEY 到官网申请

         booleanm_bKeyRight = true;

        

         //常用事件监听,用来处理通常的网络错误,授权验证错误等

                   publicstatic class MyGeneralListener implements MKGeneralListener {

                            @Override

                            publicvoid onGetNetworkState(int iError) {

                                     Toast.makeText(Location.mLocation.getApplicationContext(),"网络信号不好!",

                                                        Toast.LENGTH_LONG).show();

                            }

 

                            @Override

                            publicvoid onGetPermissionState(int iError) {

                                     if(iError == MKEvent.ERROR_PERMISSION_DENIED) {

                                               //授权Key错误:

                                               Toast.makeText(Location.mLocation.getApplicationContext(),

                                                                 "请在BMapApiDemoApp.java文件输入正确的授权Key!",

                                                                 Toast.LENGTH_LONG).show();

                                               Location.mLocation.m_bKeyRight= false;

                                     }

                            }

                           

                   }

         @Override

         publicvoid onCreate() {

                   mLocation= this;

                   mLocationClient= new LocationClient(Location.mLocation.getApplicationContext());

                   mLocationClient.registerLocationListener(myListener );

                   mBMapMan= new BMapManager(this);

                   mBMapMan.init(this.mStrKey,new MyGeneralListener());

                   super.onCreate();

         }

        

         publicvoid logMsg(String str) {

                   try{

                            locationData= str;

                   }catch (Exception e) {

                            e.printStackTrace();

                   }

         }

        

         publicclass MyLocationListenner implements BDLocationListener {

                   //定位

                   @Override

                   publicvoid onReceiveLocation(BDLocation location) {

                            if(location == null)

                                     return;

                            StringBuffersb = new StringBuffer(256);

                            sb.append("time:");

                            sb.append(location.getTime());

                            sb.append(";nerrorcode:");

                            sb.append(location.getLocType());

                            sb.append(";latitude:");

                            sb.append(location.getLatitude());

                            sb.append(";lontitude:");

                            sb.append(location.getLongitude());

                            sb.append(";radius:");

                            sb.append(location.getRadius());

                            if(location.getLocType() == BDLocation.TypeGpsLocation){

                                     sb.append(";speed:");

                                     sb.append(location.getSpeed());

                                     sb.append(";satellite:");

                                     sb.append(location.getSatelliteNumber());

                            }else if (location.getLocType() == BDLocation.TypeNetWorkLocation){

                                     sb.append(";province:");

                                     sb.append(location.getProvince());

                                     sb.append(";city:");

                                     sb.append(location.getCity());

                                     sb.append(";district:");

                                     sb.append(location.getDistrict());

                                     sb.append(";addr:");

                                     sb.append(location.getAddrStr());

                            }

                            sb.append(";sdkversion:");

                            sb.append(mLocationClient.getVersion());

                            logMsg(sb.toString());

                            Datedate = new Date();

                            Log.d("receivelocation",String.valueOf(date.getTime()));

                            slocation.latitude= location.getAltitude();

                            slocation.longitude= location.getLongitude();

                   }

                   //数据库中查询位置

                   publicvoid onReceivePoi(BDLocation poiLocation) {

                            if(poiLocation == null){

                                     return;

                            }

                            StringBuffersb = new StringBuffer(256);

                            sb.append("Poitime:");

                            sb.append(poiLocation.getTime());

                            sb.append(";errorcode:");

                            sb.append(poiLocation.getLocType());

                            sb.append(";latitude:");

                            sb.append(poiLocation.getLatitude());

                            sb.append(";lontitude:");

                            sb.append(poiLocation.getLongitude());

                            sb.append(";radius:");

                            sb.append(poiLocation.getRadius());

                            if(poiLocation.getLocType() == BDLocation.TypeNetWorkLocation){

                                     sb.append(";addr:");

                                     sb.append(poiLocation.getAddrStr());

                            }

                            if(poiLocation.hasPoi()){

                                     sb.append(";Poi:");

                                     sb.append(poiLocation.getPoi());

                            }else{                                   

                                     sb.append("noPoiinformation");

                            }

                            logMsg(sb.toString());

                   }

         }

        

         /**

          *地理位置改变后的接收消息

          */

         publicclass NotifyLister extends BDNotifyListener{

                   publicvoid onNotify(BDLocation mlocation, float distance){

                            mVibrator01.vibrate(1000);

                   }

         }

         //建议在您app的退出之前调用mapadpi的destroy()函数,避免重复初始化带来的时间消耗

                   publicvoid onTerminate() {

                            // TODO Auto-generated methodstub

                            if(mBMapMan != null) {

                                     mBMapMan.destroy();

                                     mBMapMan= null;

                            }

                            super.onTerminate();

                   }

}

第四步:在主函数中的调用,并设置GPS工具的属性

//基于地理位置的定位
private LocationClient mLocClient;

        LocationInfo.SItude station;

使用方法:

在onCreate方法中调用函数 startTheLocation()函数;

/**
* 更新软件的地址信息
*/
private void startTheLocation()
{
//使用地理位置进行定位
mLocClient = ((Location)getApplication()).mLocationClient;
((Location)getApplication()).poiData = "";
setLocationOption();
mLocClient.start();
}
//设置相关参数
private void setLocationOption(){
LocationClientOption option = new LocationClientOption();
       option.setPriority(LocationClientOption.NetWorkFirst); // 设置网络优先
option.setOpenGps(false);//打开gps
option.disableCache(true);
option.setCoorType("bd09ll"); //设置坐标类型
option.setPriority(LocationClientOption.NetWorkFirst);
option.setProdName("abc");//你的应用名称
option.setAddrType("all"); //设置地址信息,仅设置为“all”时有地址信息,默认无地址信息
option.setScanSpan(60000); //设置定位模式,小于1秒则一次定位;大于等于1秒则定时定位,设置第隔一分钟定位一次
mLocClient.setLocOption(option);
}

第五步:获取定位后的地理位置:

String strlatitude = "",strlongtitude = "";

station = ((Location)getApplication()).slocation; //获取定位信息

if(station != null)
{
strlatitude = station.latitude;
strlongtitude = station.longitude;
}


用Google地图JS在网页上的显示:

 <div id="map_canvas" style="width: 100%; height: 450px;">   </div>

    <script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?key=你的Google在图KEY&sensor=false"  charset="utf-8">
    </script>
    <script type="text/javascript" charset="utf-8" >
        var map;
        var markersArray = [];

      var beaches = null;
        var latitude, longitude;

      var poly;

 function setMarkers(locations) { 
                    var path = poly.getPath();
                    for (var i = 0; i < locations.length; i++) {
                    var beach = locations[i];
                    var strTitle = "#" + beach[3] + "; 时间:" + beach[0];
                    var myLatLng = new google.maps.LatLng(beach[1], beach[2]);
                    path.push(myLatLng);


                    if (i == 0) {
                        var image = new google.maps.MarkerImage('/Content/icons/s.png',
                        // This marker is 20 pixels wide by 32 pixels tall.
                  new google.maps.Size(20, 32),
                        // The origin for this image is 0,0.
                  new google.maps.Point(0, 0),
                        // The anchor for this image is the base of the flagpole at 0,32.
                  new google.maps.Point(10, 32));
                    }
                    else if (i == locations.length - 1) {
                        var image = new google.maps.MarkerImage('/Content/icons/e.png',
                        // This marker is 20 pixels wide by 32 pixels tall.
                  new google.maps.Size(20, 32),
                        // The origin for this image is 0,0.
                  new google.maps.Point(0, 0),
                        // The anchor for this image is the base of the flagpole at 0,32.
                  new google.maps.Point(10, 32));
                    }
                    else { 
                        var image = new google.maps.MarkerImage('/Content/icons/p.png',
                        // This marker is 20 pixels wide by 32 pixels tall.
                  new google.maps.Size(20, 32),
                        // The origin for this image is 0,0.
                  new google.maps.Point(0, 0),
                        // The anchor for this image is the base of the flagpole at 0,32.
                  new google.maps.Point(10, 32));
                    }


                    marker = new google.maps.Marker({
                        position: myLatLng,
                        map: map,
                       // shadow: shadow,
                        icon: image,
                       // shape: shape,
                        //title: beach[0],
                        title: strTitle,
                        zIndex: beach[3]
                    });
                    markersArray.push(marker);
                }
            } 
           
        // Removes the overlays from the map, but keeps them in the array
            function clearOverlays() {
              if (markersArray) {
                for (i in markersArray) {
                  markersArray[i].setMap(null);
                }
              }
            }
            // Deletes all markers in the array by removing references to them
            function deleteOverlays() {
              if (markersArray) {
                for (i in markersArray) {
                  markersArray[i].setMap(null);
                }
                markersArray.length = 0;
              }
            }
            // Shows any overlays currently in the array
            function showOverlays() {
              if (markersArray) {
                for (i in markersArray) {
                  markersArray[i].setMap(map);
                }
              }
            }


            function getLatestInitPosition(locations) {
                for (var i = 0; i < locations.length; i++) {
                    var beach = locations[i];
                    latitude = beach[1].toString();
                    longitude = beach[2].toString();
                    break;                    
                }
            }
        function updateTheTrace() {
        /**
        * Data for the markers consisting of a name, a LatLng and a zIndex for
        * the order in which these markers should display on top of each
        * other.
        */
            var myOptions = {
                zoom: 10,
                center: new google.maps.LatLng(31.2, 121.6),
                mapTypeId: google.maps.MapTypeId.ROADMAP
            };


            var polyOptions = {
                strokeColor: '#f01e50',
                strokeOpacity: 1.0,
                strokeWeight: 3
            };


            if (beaches != null&&beaches !="") {
               
                getLatestInitPosition(beaches);
                myOptions = {
                    zoom: 10,
                    center: new google.maps.LatLng(latitude, longitude),
                    mapTypeId: google.maps.MapTypeId.ROADMAP
                };
            map = new google.maps.Map(document.getElementById("map_canvas"),myOptions);
            deleteOverlays();
            poly = new google.maps.Polyline(polyOptions);
            poly.setMap(map);
            setMarkers(beaches);
             
             //setMarkers(beaches);           
            }else {
            
            map = new google.maps.Map(document.getElementById("map_canvas"),
                                myOptions);
            }
        } 


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值