使用HTML5Geolocation实现距离跟踪器
时间:2023-04-02 12:51:34
HTML
HTML5Geolocation(地理定位)用于定位用户的位置。那么如何实现距离跟踪器呢?我的想法是这样的。前提是浏览器支持h5地理定位。在此基础上获取用户位置,更新用户位置,计算距离,显示在页面上。这样简单的实现了一个距离跟踪器,让用户更清楚的看到当前位置,这里连接了百度地图API。页面结构如下所示:
纬度:经度:精度:时间戳:当前行驶距离:总行驶距离: 判断浏览器是否支持HTML5Geolocation。加载正文时调用loadDemo()方法。该方法根据navigator.geolocation判断浏览器是否支持HTML5Geolocation;如果navigator.geolocation为真,那么我们就可以开始获取和更新用户的位置了。实时获取用户位置。HTML5可以通过getCurrentPosition()方法获取用户的位置。但这只会获取一次,所以我们选择了watchPosition()方法,它返回用户的当前位置,并随着用户移动(就像汽车中的GPS)继续返回更新的位置。navigator.geolocation.watchPosition(updateLocation,handleLocationError,{timeout:10000});在不断获取位置的同时,调用updateLocation方法将位置显示在页面上,当然还要调用计算距离的方法获取距离,并不断更新百度地图上的位置。变种纬度=position.coords.latitude;varlongitude=position.coords.longitude;var准确度=position.coords.accuracy;vartimestamp=position.timestamp;document.getElementById("latitude").innerHTML="纬度:"+latitude;document.getElementById("longitude").innerHTML="经度:"+longitude;document.getElementById("accuracy").innerHTML="准度:"+accuracy;document.getElementById("timestamp").innerHTML="时间戳:"+timestamp;if(accuracy>=30000){updateStatus("需要更准确的值来计算距离。");返回;}if((lastLat!=null)&&(lastLong!=null)){varcurrentDistance=distance(latitude,longitude,lastLat,lastLong);document.getElementById("currDist").innerHTML="当前行驶距离:"+currentDistance.toFixed(2)+"km";总距离+=当前距离;document.getElementById("totalDist").innerHTML="总行程:"+currentDistance.toFixed(2)+"km";updateStatus("位置更新成功。");}lastLat=纬度;lastLong=经度;以起始位置和当前位置的经度计算距离纬度作为参数放入函数,通过换算计算距离(单位为千米)Number.prototype.toRadians=function(){returnthis*数学.PI/180;}functiondistance(latitude1,longitude1,latitude2,longitude2){varR=6371;vardeltaLatitude=(latitude2-latitude1).toRadians();vardeltaLongitude=(longitude2-longitude1).toRadians();latitude1=latitude1.toRadians(),latitude2=latitude2.toRadians();变量a=数学.sin(deltaLatitude/2)*Math.sin(deltaLatitude/2)+Math.cos(latitude1)*Math.cos(latitude2)*Math.sin(deltaLongitude/2)*Math.sin(deltaLongitude/2);c=2*Math.atan2(Math.sqrt(a),Math.sqrt(1-a));vard=R*c;返回d;}百度地图API接入使用百度地图API,您需要注册百度账号,申请成为百度开发者,并获得使用相关服务的密钥。根据文档,你可以知道如何使用这个API代码如下:varmap=newBMap.Map("allmap");//创建一个地图实例map.centerAndZoom(newBMap.Point(longitude,latitude),14);//设置中心点坐标和地图层级map.addControl(newBMap.MapTypeControl());//添加地图类型控件map.setCurrentCity("南昌");//显示城市,必须设置此项map.enableScrollWheelZoom(true);//启用鼠标滚轮缩放//下面是当前位置标签设置varpoint=newBMap.Point(longitude,latitude);map.centerAndZoom(点,14);varmarker=newBMap.Marker(point);//创建一个标记map.addOverlay(marker);//将标记添加到地图marker.setAnimation(BMAP_ANIMATION_BOUNCE);//弹跳动画//百度地图API函数--------结束记得先引入一个script标签效果展示我的博客,欢迎交流!源代码点这里