您当前的位置: 首页 > 学无止境 > 心得笔记 网站首页心得笔记
百度地图javascript接口开发-获取所在城市及基于浏览器位置获取
发布时间:2016-11-20 14:28:03编辑:雪饮阅读()
获取所在城市示例:
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>无标题文档</title>
<style type="text/css">
html{height:100%;}
body{height:100%;margin:0px;padding:0px;}
#container{
clear:both;
height:100%;
width:100%;
}
</style>
<script type="text/javascript" src="http://api.map.baidu.com/api?v=2.0&ak=s9vYSVwPjtPFv00vuxKzoNxD"></script>
<script type="text/javascript">
BMap.Point.prototype.toString=function(){
return "当前的经度="+this.lng+",纬度="+this.lat;
}
BMap.Pixel.prototype.toString=function(){
return "当前点坐标x="+this.x+",y="+this.y;
}
var map;
function InitMap(){
map=new BMap.Map("container");
var point=new BMap.Point(104.06,30.67);//成都的经纬度点
map.centerAndZoom(point,12);
map.enableScrollWheelZoom();
var options={
renderOptions:{
map:map,
},
};
var localCity=new BMap.LocalCity(options);
localCity.get(function(localCityResult){
var center_poi=localCityResult.center;//Point类型
console.log("城市名称:"+localCityResult.name);
console.log("最佳地图级别:"+localCityResult.level);
console.log("中心坐标:"+center_poi);
//当前城市的中心坐标,请无视上面成都的经纬度,会自动获取当前用户所在城市的坐标
//var marker=new BMap.Marker(center_poi);
//map.addOverlay(marker);
//map.setCenter(center_poi);
});
map.addEventListener("click",function(event){
//console.log(event.point);
});
}
</script>
</head>
<body onLoad="InitMap();">
<div id="container"></div>
<div id="result"></div>
</body>
</html>
获取当前位置示例:
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>无标题文档</title>
<style type="text/css">
html{height:100%;}
body{height:100%;margin:0px;padding:0px;}
#container{
clear:both;
height:100%;
width:100%;
}
</style>
<script type="text/javascript" src="http://api.map.baidu.com/api?v=2.0&ak=s9vYSVwPjtPFv00vuxKzoNxD"></script>
<script type="text/javascript">
BMap.Point.prototype.toString=function(){
return "当前的经度="+this.lng+",纬度="+this.lat;
}
BMap.Pixel.prototype.toString=function(){
return "当前点坐标x="+this.x+",y="+this.y;
}
var map;
function InitMap(){
map=new BMap.Map("container");
var point=new BMap.Point(104.06,30.67);//成都的经纬度点
map.centerAndZoom(point,12);
map.enableScrollWheelZoom();
var positionOptions={
enableHighAccuracy:true,
timeout:3000,
maximumAge:0
};
var geolocation=new BMap.Geolocation();
geolocation.getCurrentPosition(function(geolocationResult){
if(geolocationResult!=null){
var point=geolocationResult.point;
alert("定位的结果是:"+point);
alert("定位的精确度是:"+geolocationResult.accuracy+"米");//貌似手机上ok,pc上会出现“null米”
var marker=new BMap.Marker(point);
map.addOverlay(marker);
map.setCenter(point);
}
},positionOptions);
map.addEventListener("click",function(event){
//console.log(event.point);
});
}
</script>
</head>
<body onLoad="InitMap();">
<div id="container"></div>
<div id="result"></div>
</body>
</html>
关键字词:百度地图api,javascript