博主最近进行一款APP开发,需要用到定位功能,经过一番折腾,终于搞定,不废话,代码如下
mui.plusReady(function() { var longitude, latitude; //var map = new BMap.Map("container"); // navigator.geolocation.getCurrentPosition(function(position) { // longitude = position.coords.longitude; // latitude = position.coords.latitude; // // console.log("longitude:" + longitude + "==latitude:" + latitude); // var point = new BMap.Point(longitude, latitude); // map.centerAndZoom(point, 20); // 初始化地图,设置中心点坐标和地图级别 // var marker = new BMap.Marker(point); // 创建标注 // map.addOverlay(marker); // 将标注添加到地图中 // map.panTo(point); // }); plus.geolocation.getCurrentPosition(translatePoint, function(e) { mui.toast("异常:" + e.message); }); function translatePoint(position) { var currentLon = position.coords.longitude; var currentLat = position.coords.latitude; var gpsPoint = new BMap.Point(currentLon, currentLat); BMap.Convertor.translate(gpsPoint, 2, initMap); //坐标转换 } function initMap(point) { map = new BMap.Map("container"); //创建地图 map.addControl(new BMap.NavigationControl()); map.addControl(new BMap.ScaleControl()); map.addControl(new BMap.OverviewMapControl()); map.centerAndZoom(point, 15); map.addOverlay(new BMap.Marker(point)); } // setTimeout(function() { // var gpsPoint = new BMap.Point(longitude, latitude); // BMap.Convertor.translate(gpsPoint, 0, function(point) { // var geoc = new BMap.Geocoder(); // geoc.getLocation(point, function(rs) { // var addComp = rs.addressComponents; // mui.alert(addComp.province + ", " + addComp.city + ", " + addComp.district + ", " + addComp.street + ", " + addComp.streetNumber); // }); // }); // }, 3000); });
注意,在使用过程中,需要引入百度地图的JS
<script type="text/javascript" src="http://api.map.baidu.com/api?v=2.0&ak=开发者key"></script>
<script type="text/javascript" src="http://developer.baidu.com/map/jsdemo/demo/convertor.js"></script>
其中,开发者key需要自己去百度地图开发者平台申请,此处教程上链接http://lbsyun.baidu.com/index.php?title=androidsdk/guide/key