admin管理员组

文章数量:1529449

浏览器定位 :这里用了两种 ,一种是Html5自带的方法 另一种是引用了百度api  ,百度api 的使用有三种:

1 浏览器定位

2 ip定位

3 SDK辅助定位

引用百度api的前提是需要申请百度ak,这个大家自行百度查询吧  使用百度的话需要连接外网

下面是代码 

<!DOCTYPE html>
<html>
<title>测试PC浏览器定位</title>
<body>
	<p id="demo">点击这个按钮,通过H5获得您的坐标:</p>
	<div id="allmap"></div>
	<button onclick="getLocation()">H5测试</button>

	<script src="../../js/lib/jquery/jquery.min.js"></script>
	<script type="text/javascript"
		src="http://api.map.baidu/api?v=3.0&ak=你的ak码"></script>
	<script>
	
	
		/* H5定位方法 */
		var x = document.getElementById("demo");
		function getLocation() {
			if (navigator.geolocation) {
				navigator.geolocation.getCurrentPosition(showPosition,
						showError);
			} else {
				console.log("请求失败")
			}
		}
		function showPosition(position) {
			console.log(position.coords.latitude + "   "
					+ position.coords.longitude)
		}
		function showError(error) {
			console.log("H5错误编码  " + error.code)

			switch (error.code) {
			case error.PERMISSION_DENIED:
				x.innerHTML = "User denied the request for Geolocation."
				break;
			case error.POSITION_UNAVAILABLE:
				x.innerHTML = "Location information is unavailable."
				break;
			case error.TIMEOUT:
				x.innerHTML = "The request to get user location timed out."
				break;
			case error.UNKNOWN_ERROR:
				x.innerHTML = "An unknown error occurred."
				break;
			}
		}
		
		
		
		/* 百度api 通过浏览器定位 */
		var geolocation1 = new BMap.Geolocation();
		geolocation1.getCurrentPosition(function(r) {
			if (this.getStatus() == BMAP_STATUS_SUCCESS) {
				var mk = new BMap.Marker(r.point);
				alert('浏览器定位您的位置:' + r.point.lng + ',' + r.point.lat);
			} else {
				alert('浏览器定位 failed 状态  ' + this.getStatus());
			}
		});

		
		//百度api 通过ip定位
		function myFun(result) {
			var cityName = result.name;
			alert("IP 定位城市:" + cityName+"   经度"+result.center.lng+"   纬度"+result.center.lat);
		}
	 	var myCity = new BMap.LocalCity();
		myCity.get(myFun); 
		
		
	 	
		//百度api SDK辅助定位
		var geolocation = new BMap.Geolocation();
		// 开启SDK辅助定位
		geolocation.enableSDKLocation();
		geolocation.getCurrentPosition(function(r) {
			if (this.getStatus() == BMAP_STATUS_SUCCESS) {
				var mk = new BMap.Marker(r.point);
				alert('SDK辅助定位 您的位置:' + r.point.lng + ',' + r.point.lat);
			} else {
				alert('SDK辅助failed  状态' + this.getStatus());
			}
		}); 
	</script>
</body>
</html>

 

 

 

本文标签: 浏览器PC