Home > Web Front-end > H5 Tutorial > body text

html5定位获取当前位置并在百度地图上显示_html5教程技巧

php.cn
Release: 2016-05-16 15:47:26
original
2373 people have browsed it

在开发移动端 web 或者webapp时,使用百度地图 API 的过程中,经常需要通过手机定位获取当前位置并在地图上居中显示出来,这就需要用到html5的地理定位功能。

复制代码
代码如下:

navigator.geolocation.getCurrentPosition(callback);

在获取坐标成功之后会执行回调函数 callback; callback 方法的参数就是获取到的坐标点;然后可以初始化地图,设置控件、中心点、缩放等级,然后给地图添加point的overlay:

复制代码
代码如下:

var map = new BMap.Map("mapDiv");//mapDiv为放地图的 div 的 id
map.addControl(new BMap.NavigationControl());
map.addControl(new BMap.ScaleControl());
map.addControl(new BMap.OverviewMapControl());
map.centerAndZoom(point, 15);//point为坐标点,15为地图缩放级别,最大级别是 18
var pointMarker = new BMap.Marker(point);
map.addOverlay(pointMarker);

然而事实上这样还不够,显示出来的结果并不准,这是因为 getCurrentPosition 获取到的坐标是 GPS 经纬度坐标,而百度地图的坐标是经过特殊转换的,所以,在获取定位坐标和初始化地图之间需要进行一步坐标转换工作,该转换方法百度API里面已经提供了,转换一个点或者批量装换的方法均有提供:单个点转换需引用 http://developer.baidu.com/map/jsdemo/demo/convertor.js,批量转换需引用 http://developer.baidu.com/map/jsdemo/demo/changeMore.js,这里只需要前者即可:

复制代码
代码如下:

BMap.Convertor.translate(gpsPoint, 0, callback);
//gpsPoint:转换前坐标,第二个参数为转换方法,0表示gps坐标转换成百度坐标,callback回调函数,参数为新坐标点

例子的详细代码如下:(引用中的ak是申请的key)

复制代码
代码如下:


















本人开发过程中觉得电脑的定位速度有点慢,经常无法获取坐标导致地图无法显示,建议用手机测试,定位较快。

当然了,如果仅是开发移动端的网页,就不需要使用jQuery,框架太大,可以换用其他轻量级的移动端的 js 框架。
Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact [email protected]
Latest issues
Popular Tutorials
More>
Latest downloads
More>
web effects
Website source code
Website materials
Front end template
About us Disclaimer Sitemap
PHP Chinese website:Public welfare online PHP training,Help PHP learners grow quickly!