考拉~

导航

 

  1.生活中自动定位的使用场景:  

  (1)百度、谷歌地图已成为我们出行的必备助手,其中会获取当前的位置

  (2)各公司的签到软件,为防止小伙伴们修改签到地点会采用自动定位等

  2.自动定位基础原理:

  移动端接受卫星信号,获取当前手机的地理位置(经度与纬度),然后依据经纬度反射出当前位置的实际地址(pc端浏览器暂不支持此功能)

  3.前端开发

  我们可以通过调用谷歌或者百度的定位接口,来获取自己的当前位置

  (1)html部分

	     <div class="weui_cell">
	         <div class="weui_cell_hd"><label  id="latlon">位置</label></div>
	         <div class="weui_cell_bd weui_cell_primary">
	         	<textarea class="weui_textarea  address" id="baidu_geo">定位中...</textarea> 
	         </div>
	     </div>

  (2)js部分

<script type="text/javascript">
    $(function () {
        if (navigator.geolocation) {
            navigator.geolocation.getCurrentPosition(showPosition, locationError);
        } else {
            alert("你的浏览器不支持 GeoLocation.");
        }
    });

    //定位成功时,执行的函数
function showPosition(position){
	//$("#latlon").html("纬度:"+position.coords.latitude +',经度:'+ position.coords.longitude);
	var Wei=position.coords.latitude;
	var Jing=position.coords.longitude; 
	var latlon = position.coords.latitude+','+position.coords.longitude;
	
	//baidu
	//var url = "http://api.map.baidu.com/geocoder/v2/?ak=C93b5178d7a8ebdb830b9b557abce78b&callback=renderReverse&location="+latlon+"&output=json&pois=0";
	var  url ="http://api.map.baidu.com/geocoder/v2/?callback=renderReverse&location="+Wei+","+Jing+"&output=json&pois=1&ak=UcxbIt99PwqVOOYWTDbGZxHkHkSGrvYB";
	$.ajax({ 
		type: "GET", 
		dataType: "jsonp", 
		url: url,
		beforeSend: function(){
			$("#baidu_geo").val('正在定位...');
		},
		success: function (json) { 
			if(json.status==0){
			 var sxCity=json.result.formatted_address;
			 var sBusiness=json.result.business;
 			 var sDecematic=json.result.sematic_description;
 			 var sAddress=sxCity+sBusiness+sDecematic;
				$("#baidu_geo").val( sAddress);
			}
		},
		error: function (XMLHttpRequest, textStatus, errorThrown) { 
			$("#baidu_geo").val(latlon+"地址位置获取失败"); 
		}
	});
}
    // 定位失败时,执行的函数
    function locationError(error) {
        switch (error.code) {
            case error.PERMISSION_DENIED:
                alert("User denied the request for Geolocation.");
                break;
            case error.POSITION_UNAVAILABLE:
                alert("Location information is unavailable.");
                break;
            case error.TIMEOUT:
                alert("The request to get user location timed out.");
                break;
            case error.UNKNOWN_ERROR:
                alert("An unknown error occurred.");
                break;
        }
    }
</script>

  有以上2部分,我们编写的前端界面就会自动定位当前位置。

posted on 2018-02-08 09:56  考拉~  阅读(120)  评论(0编辑  收藏  举报