关于html5获取用户地理位置

时间:2023-03-10 03:38:35
关于html5获取用户地理位置
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8"/>
<title>基于浏览器的HTML5查找地理位置</title>
<!-- 百度API -->
<script src="http://api.map.baidu.com/api?v=1.4" type="text/javascript"></script>
<script> // void getCurrentPosition(onSuccess,onError,options);
//获取用户当前位置 // int watchCurrentPosition(onSuccess,onError,options);
//持续获取当前用户位置 // void clearWatch(watchId);
//watchId 为watchCurrentPosition返回的值
//取消监控 //options = {
// enableHighAccuracy,   //boolean 是否要求高精度的地理信息
// timeout,         //表示等待响应的最大时间,默认是0毫秒,表示无穷时间
// maximumAge        /应用程序的缓存时间
//}     function getLocation(){
var options={
enableHighAccuracy:true,
maximumAge:1000
}
if(navigator.geolocation){
//浏览器支持geolocation
navigator.geolocation.getCurrentPosition(onSuccess,onError,options); }else{
//浏览器不支持geolocation
}
} //成功时
function onSuccess(position){
//返回用户位置
//经度
var longitude =position.coords.longitude+0.008774687519; ;
//纬度
var latitude = position.coords.latitude+0.00374531687912; //使用百度地图API
//创建地图实例
var map =new BMap.Map("container"); //创建一个坐标
var point =new BMap.Point(longitude,latitude);
//地图初始化,设置中心点坐标和地图级别
map.centerAndZoom(point,15);
map.enableScrollWheelZoom(true);
var marker = new BMap.Marker(point); // 创建标注
map.addOverlay(marker); // 将标注添加到地图中 } //失败时
function onError(error){
switch(error.code){
case 1:
alert("位置服务被拒绝");
break; case 2:
alert("暂时获取不到位置信息");
break; case 3:
alert("获取信息超时");
break; case 4:
alert("未知错误");
break;
} } window.onload=getLocation;
</script>
</head>
<body> <div id="container" style="width:600px;height:600px"></div>
</body>
</html>