先上代码吧
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script type="text/javascript" src="https://api.map.baidu.com/api?v=2.0&ak=7a6QKaIilZftIMmKGAFLG7QT1GLfIncg"></script>
</head>
<style>
* {
margin: 0;
padding: 0;
}
html,
body {
width: 100%;
height: 100%;
}
article {
width: 65%;
height: 95%;
background-color: aquamarine;
background-color: #efeeee;
box-shadow: 2px 2px 2px rgba(0, 0, 0, .2),
-2px -2px 20px rgba(225, 225, 225, 1);
}
body,
article {
display: flex;
flex-direction: column;
justify-content: space-evenly;
align-items: center;
}
.geoInfo {
width: 60%;
height: 60%;
border: 3px dashed rgb(85, 98, 110);
}
</style>
<body>
<article>
<h1>地图API</h1>
<div class="geoInfo" id="geoInfo"></div>
</article>
</body>
<script type="text/javascript">
// 获取存放地图的容器
var geoInfo = document.querySelector('#geoInfo');
// 创建地图实例
var map = new BMap.Map("geoInfo");
var geolocation = new BMap.Geolocation();
// 利用浏览器的定位功能(别问原理,开发文档上就这么写的)
geolocation.getCurrentPosition(function (e) {
if (this.getStatus() == BMAP_STATUS_SUCCESS) {
// console.log(e.point.lng); e.point.lng: 定位得到的经度
// console.log(e.point.lat); e.point.lat: 定位得到的纬度
// 地图初始化,同时设置地图展示级别(15)
map.centerAndZoom(new BMap.Point(e.point.lng, e.point.lat), 15);
} else {
// 错误就在容器输出 false
geoInfo.innerHTML = 'false';
}
});
</script>
</html>
需要说明一下,第八行引入百度API的代码,后面ak里的内容是我自己在百度地图开放平台申请的,大家要是练习或者做测试的话,建议是自己去申请一个。
百度地图申请ak
然后把ak后面的内容换成自己申请的,其他的就,,,还请谨慎改动。