在Google Maps API上使用LatLngBounds,可以通过以下步骤实现:
<head>
标签中添加以下代码,以导入Google Maps API库。<script src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY"></script>
请将YOUR_API_KEY
替换为您自己的Google Maps API密钥。
google.maps.Map
类创建一个地图对象,并将其绑定到HTML页面的特定元素上。var map = new google.maps.Map(document.getElementById('map'), {
center: {lat: 37.7749, lng: -122.4194}, // 设置地图的中心点坐标
zoom: 12 // 设置地图的缩放级别
});
在上述代码中,'map'
是HTML页面中用于显示地图的元素的ID。您可以根据需要进行更改。
google.maps.LatLngBounds
类创建一个LatLngBounds对象,该对象将用于定义地图视图的边界框。var bounds = new google.maps.LatLngBounds();
LatLngBounds
对象的extend
方法,将坐标点添加到边界框中。var point1 = new google.maps.LatLng(37.7749, -122.4194);
var point2 = new google.maps.LatLng(37.7895, -122.3892);
bounds.extend(point1);
bounds.extend(point2);
在上述代码中,point1
和point2
是您要添加到边界框的坐标点。您可以根据需要添加更多的坐标点。
fitBounds
方法,将地图视图调整为适合边界框的大小。map.fitBounds(bounds);
<!DOCTYPE html>
<html>
<head>
<title>Google Maps API - LatLngBounds</title>
<script src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY"></script>
<style>
#map {
height: 400px;
width: 100%;
}
</style>
</head>
<body>
<div id="map"></div>
<script>
function initMap() {
var map = new google.maps.Map(document.getElementById('map'), {
center: {lat: 37.7749, lng: -122.4194},
zoom: 12
});
var bounds = new google.maps.LatLngBounds();
var point1 = new google.maps.LatLng(37.7749, -122.4194);
var point2 = new google.maps.LatLng(37.7895, -122.3892);
bounds.extend(point1);
bounds.extend(point2);
map.fitBounds(bounds);
}
</script>
<script async defer src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&callback=initMap"></script>
</body>
</html>
请将YOUR_API_KEY
替换为您自己的Google Maps API密钥。
这样,您就可以在Google Maps API上使用LatLngBounds来定义地图视图的边界框,并将地图视图调整为适合边界框的大小。
领取专属 10元无门槛券
手把手带您无忧上云