13 google-maps google-maps-api-3
我想要一张大的柏林地图,你可以看到多条路线.不幸的是,DirectionsRenderer会缩放到路线,因此您必须再次手动缩小.
我该如何避免这种行为?
var $canvas = document.querySelector('#map');
var map = new google.maps.Map($canvas, {
center: new google.maps.LatLng(52.46004869999999, 13.37898690),
mapTypeId: google.maps.MapTypeId.ROADMAP,
zoom: 14
});
var routes = [
{
origin: new google.maps.LatLng(52.459281, 13.356367),
destination: new google.maps.LatLng(52.455833, 13.322948),
travelMode: google.maps.TravelMode.BICYCLING
},
{
origin: new google.maps.LatLng(52.597621, 13.430536),
destination: new google.maps.LatLng(52.5918799, 13.2832929),
travelMode: google.maps.TravelMode.BICYCLING
}
];
routes.forEach(function(route) {
new google.maps.DirectionsService().route(route, function(body) {
var display = new google.maps.DirectionsRenderer();
display.setMap(map);
display.setDirections(body);
});
});
Run Code Online (Sandbox Code Playgroud)
geo*_*zip 30
使用DirectionsRenderer的preserveViewport选项阻止自动缩放到路径,然后设置您喜欢的视口.
{preserveViewport: true}
Run Code Online (Sandbox Code Playgroud)
或者,如果需要,计算方向响应边界的并集,并使地图适合该方法.
var bounds = new google.maps.LatLngBounds();
routes.forEach(function(route) {
new google.maps.DirectionsService().route(route, function(body) {
var display = new google.maps.DirectionsRenderer({preserveViewport: true});
display.setMap(map);
display.setDirections(body);
bounds.union(body.routes[0].bounds);
map.fitBounds(bounds);
});
});
Run Code Online (Sandbox Code Playgroud)
代码段:
var $canvas = document.querySelector('#map');
var map = new google.maps.Map($canvas, {
center: new google.maps.LatLng(52.46004869999999, 13.37898690),
mapTypeId: google.maps.MapTypeId.ROADMAP,
zoom: 14
});
var routes = [{
origin: new google.maps.LatLng(52.459281, 13.356367),
destination: new google.maps.LatLng(52.455833, 13.322948),
travelMode: google.maps.TravelMode.BICYCLING
},
{
origin: new google.maps.LatLng(52.597621, 13.430536),
destination: new google.maps.LatLng(52.5918799, 13.2832929),
travelMode: google.maps.TravelMode.BICYCLING
}
];
var bounds = new google.maps.LatLngBounds();
routes.forEach(function(route) {
new google.maps.DirectionsService().route(route, function(body) {
var display = new google.maps.DirectionsRenderer({
preserveViewport: true
});
display.setMap(map);
display.setDirections(body);
bounds.union(body.routes[0].bounds);
map.fitBounds(bounds);
});
});Run Code Online (Sandbox Code Playgroud)
html,
body,
div#map {
height: 100%;
width: 100%;
padding: 0px;
margin: 0px;
}Run Code Online (Sandbox Code Playgroud)
<div id="map"></div>
<script src="https://maps.googleapis.com/maps/api/js"></script>Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
5706 次 |
| 最近记录: |