CSS 样式:
css
map {width: 100vw;height: 100vh;
}sidebar {position: absolute;top: 0;left: 0;padding: 10px;background-color: fff;
}search {position: absolute;top: 0;right: 0;padding: 10px;background-color: fff;
}search-input {width: 200px;padding: 5px;
}search-button {padding: 5px;
}results {position: absolute;top: 40px;right: 0;width: 300px;background-color: fff;
}results ul {list-style-type: none;padding: 0;
}results li {padding: 5px;
}JavaScript 脚本:
javascript
// 初始化地图
const map = new google.maps.Map(document.getElementById('map'), {center: { lat: 28.2282, lng: 112.9388 },zoom: 12
});// 添加点击事件监听器
map.addListener('click', function(e) {// 获取标记位置const lat = e.latLng.lat();const lng = e.latLng.lng();// 创建标记const marker = new google.maps.Marker({position: { lat, lng },map: map});// 创建信息窗口const infoWindow = new google.maps.InfoWindow({content: `位置: ${lat}, ${lng}`});// 打开信息窗口infoWindow.open(map, marker);
});// 初始化搜索框
const searchInput = document.getElementById('search-input');
const searchButton = document.getElementById('search-button');
const results = document.getElementById('results');// 添加搜索事件监听器
searchButton.addEventListener('click', function() {// 获取搜索查询const query = searchInput.value;// 向地图API发起请求const service = new google.maps.places.AutocompleteService();service.getPlacePredictions({ input: query },function(predictions, status) {if (status === 'OK') {// 清空结果列表results.innerHTML = '';// 创建结果列表predictions.forEach(prediction => {const li = document.createElement('li');li.innerHTML = prediction.description;// 添加点击事件监听器li.addEventListener('click', function() {// 获取预测位置const placeId = prediction.place_id;// 向地图API发起请求const service = new google.maps.places.PlacesService(map);service.getDetails({ placeId }, function(place, status) {if (status === 'OK') {// 创建标记const marker = new google.maps.Marker({position: place.geometry.location,map: map});// 创建信息窗口const infoWindow = new google.maps.InfoWindow({content: place.name});// 打开信息窗口infoWindow.open(map, marker);// 缩放地图map.setZoom(15);map.setCenter(place.geometry.location);}});});// 将结果添加到列表中results.appendChild(li);});}});
});这个 HTML、CSS 和 JavaScript 代码一起实现了长沙电子地图,该地图具有以下功能:地图交互:用户可以点击地图上的位置以获取标记信息,放大或缩小地图,浏览不同的区域。位置搜索:用户可以使用搜索框查找特定位置,并在地图上显示匹配结果。点击标记:用户可以点击地图上的标记以打开一个信息窗口,其中包含标记位置的详细信息。