我正在使用我存储的数据对象在Google地图中创建路线:
routeData = {
origin: 'address A',
destination: 'address B',
travelMode: google.maps.DirectionsTravelMode.DRIVING,
waypoints: [obj, obj, obj],
optimizeWaypoints: false
};
因为我在这张地图上也有其他对象,所以我设置了optimizeWaypoints: false
。
然后我使用此代码绘制路线:
// Instantiate a directions service.
var directionsService = new google.maps.DirectionsService;
// Create a renderer for directions and bind it to the map.
directionsDisplay = new google.maps.DirectionsRenderer({
preserveViewport: true,
suppressMarkers: true,
map: map
});
directionsService.route(routeData, function(result, status) {
directionsDisplay.setDirections(result);
});
directionsDisplay
是一个全局变量。
当在地图上绘制了所有对象时,我会全部浏览它们以获得边界。
fitMapObjectBounds: function(mapData){
var bounds = new google.maps.LatLngBounds();
var marker, circle, route = null;
var fitTheBounds = false;
// Marker
$(mapData.markers).each(function(key, value){
marker = new google.maps.Marker(value);
bounds.extend(marker.getPosition());
fitTheBounds = true;
});
// Circles
$(mapData.circles).each(function(key, value){
circle = new google.maps.Circle(value);
bounds.union(circle.getBounds());
fitTheBounds = true;
});
if(fitTheBounds == true) {
map.fitBounds(bounds);
}
}
我的问题是,我如何获得路线的界限?我真的找不到一个很好的例子。
更新
所以我在我的fitMapObjectBounds
函数中添加了这段代码,但它不起作用:
directionsService = new google.maps.DirectionsService;
directionsService.route(mapData.routeStreet, function(result, status) {
directionsDisplay.setDirections(result);
bounds.union(directionsDisplay.getDirections().routes[0].bounds);
});
答案 0 :(得分:2)
默认显示的路线边界(返回的第一个路线)是
directionsDisplay.getDirections().routes[0].bounds
代码段
function initialize() {
var map = new google.maps.Map(
document.getElementById("map_canvas"), {
center: new google.maps.LatLng(37.4419, -122.1419),
zoom: 13,
mapTypeId: google.maps.MapTypeId.ROADMAP
});
var routeData = {
origin: 'New York, NY',
destination: 'Philadelphia, PA',
travelMode: google.maps.DirectionsTravelMode.DRIVING,
waypoints: [],
optimizeWaypoints: false
};
// Instantiate a directions service.
var directionsService = new google.maps.DirectionsService;
// Create a renderer for directions and bind it to the map.
directionsDisplay = new google.maps.DirectionsRenderer({
preserveViewport: true,
suppressMarkers: true,
map: map
});
directionsService.route(routeData, function(result, status) {
directionsDisplay.setDirections(result);
map.fitBounds(directionsDisplay.getDirections().routes[0].bounds);
});
// fitObjectBounds()
}
google.maps.event.addDomListener(window, "load", initialize);

html,
body,
#map_canvas {
height: 100%;
width: 100%;
margin: 0px;
padding: 0px
}

<script src="https://maps.googleapis.com/maps/api/js"></script>
<div id="map_canvas"></div>
&#13;