html嵌入百度地图
html嵌入百度地图
key地址
https://lbsyun.baidu.com/apiconsole/key#/home ,点进去注册应用、然后复制key换掉即可显示地图
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>百度地图搜索示例</title>
<style>
body {
font-family: Arial, sans-serif;
margin: 0;
padding: 20px;
}
h1 {
text-align: center;
color: #333;
}
#search-container {
text-align: center;
margin-bottom: 20px;
}
#search-input {
width: 300px;
padding: 10px;
font-size: 16px;
}
#search-button {
padding: 10px 20px;
font-size: 16px;
background-color: #4CAF50;
color: white;
border: none;
cursor: pointer;
}
#mapcontainer {
width: 80%;
height: 400px;
margin: 0 auto;
border: 1px solid #ccc;
border-radius: 5px;
}
</style>
</head>
<body>
<h1>百度地图搜索示例</h1>
<div id="search-container">
<input type="text" id="search-input" placeholder="输入地点名称">
<button id="search-button">搜索</button>
</div>
<div id="mapcontainer"></div>
<script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.7.1/jquery.js"></script>
<script type="text/javascript" src="https://api.map.baidu.com/api?v=3.0&ak=***********"></script>
<script>
$(document).ready(function() {
var map = new BMap.Map("mapcontainer", {
coordsType: 5
});
var point = new BMap.Point(116.404, 39.915);
map.centerAndZoom(point, 11);
map.enableScrollWheelZoom(true);
var marker = new BMap.Marker(point);
map.addOverlay(marker);
// 添加搜索功能
function searchLocation() {
var local = new BMap.LocalSearch(map, {
renderOptions: {map: map},
onSearchComplete: function(results) {
if (local.getStatus() == BMAP_STATUS_SUCCESS) {
var firstResult = results.getPoi(0);
if (firstResult) {
point = firstResult.point;
map.centerAndZoom(point, 15);
marker.setPosition(point);
console.log("搜索结果:", firstResult.title, point.lat, point.lng);
} else {
console.log("未找到结果");
}
} else {
console.log("搜索失败");
}
}
});
var keyword = $("#search-input").val();
local.search(keyword);
}
// 绑定搜索按钮点击事件
$("#search-button").click(searchLocation);
// 绑定输入框回车事件
$("#search-input").keypress(function(e) {
if (e.which == 13) {
searchLocation();
}
});
// 点击地图事件
map.addEventListener("click", function(e){
var clickedLat = e.point.lat;
var clickedLng = e.point.lng;
console.log("点击位置:", clickedLat, clickedLng);
marker.setPosition(new BMap.Point(clickedLng, clickedLat));
var geoc = new BMap.Geocoder();
geoc.getLocation(e.point, function(rs){
var addComp = rs.addressComponents;
var address = addComp.province + addComp.city + addComp.district + addComp.street + addComp.streetNumber;
console.log("地址信息:", address);
});
});
});
</script>
</body>
</html>