我们是否可以创建具有两个地址位置的地图,而不需要地图中心

问题描述:

我需要创建一个Google地图,其中包含要在Google地图上显示的路线的两个地址。我没有中心。 Google Map是根据这两个地址计算中心还是强制指定一个中心?我们是否可以创建具有两个地址位置的地图,而不需要地图中心

您可以在初始化地图时使用任何虚拟位置。如果您知道两点的坐标,则可以使用LatLngBounds确保两个点都显示在地图上。

var bounds = new google.maps.LatLngBounds(); 
bounds.extend(latlng1); 
bounds.extend(latlng2); 
map.fitBounds(bounds); 

这个代码采取两个点,并确保谷歌地图检视区既包括这些点,同时显示。因此你不需要计算中心。

+0

谢谢久胜你的回应。这真的很有用。 – Deepjyot

如果您使用的是Gooogle Maps Javascript API v3directions service,那么默认情况下,该地图集中显示整个路线。

var directionsDisplay; 
var directionsService = new google.maps.DirectionsService(); 
var map; 

    function initialize() { 
     directionsDisplay = new google.maps.DirectionsRenderer(); 
     var mapOptions = {}; 
     map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions); 
     directionsDisplay.setMap(map); 
     calcRoute(); 
    } 

    function calcRoute() { 
     var start = 'Chicago, IL'; 
     var end = 'St Louis, MO'; 
     var request = { 
      origin:start, 
      destination:end, 
      travelMode: google.maps.TravelMode.DRIVING 
     }; 
     directionsService.route(request, function(response, status) { 
     if (status == google.maps.DirectionsStatus.OK) { 
      directionsDisplay.setDirections(response); 
     } 
     }); 
    } 

    google.maps.event.addDomListener(window, 'load', initialize); 

working example

+0

谢谢geocodezip。你的回应非常有用。 – Deepjyot