2016-03-06 23 views
-1

我一直在尋找一段時間.... 我有一個Polyline,路徑來自google.maps.geometry.encoding.decodePath獲取已解碼路徑谷歌地圖的中心

現在我想圍繞該路徑圍繞我的地圖,即使我不知道路徑的位置。

我該怎麼做?

我的代碼:

decodedPath = google.maps.geometry.encoding.decodePath(mapid); 

var myLatlng = new google.maps.LatLng(0, 0); 
let map = new google.maps.Map(document.getElementById(id), { 
    zoom: 1, 
    center: myLatlng, 
    mouseWheel:true 
}); 

let poly = new google.maps.Polyline({ 
    strokeColor: '#000', 
    strokeOpacity: 1.0, 
    strokeWeight: 3, 
    paths: decodedPath, 
}); 

poly.setMap(map); 
+0

好,我知道了...... decodedpath [位置] .lat() – waah

+0

你可以回答你自己的問題,並接受解決方案。 – bastelflp

回答

0

添加在解碼的路徑點到一個空google.maps.LatLngBounds對象,然後調用該對象的邊界上map.fitBounds

var bounds = new google.maps.LatLngBounds(); 
for (var i=0; i<decodedPath.length; i++) { 
    bounds.extend(decodedPath[i]); 
} 
map.fitBounds(bounds); 

proof of concept fiddle

代碼片段:'

var geocoder; 
 
var map; 
 
var mapid = "aq|rFttwdQiizCfl}[email protected]_jfBff}@silAdfdDl`[email protected][email protected]`@[email protected]"; 
 
var id = "map_canvas"; 
 

 
function initialize() { 
 
    decodedPath = google.maps.geometry.encoding.decodePath(mapid); 
 

 
    var myLatlng = new google.maps.LatLng(0, 0); 
 
    map = new google.maps.Map(document.getElementById(id), { 
 
    zoom: 1, 
 
    center: myLatlng, 
 
    mouseWheel: true 
 
    }); 
 

 
    var poly = new google.maps.Polyline({ 
 
    strokeColor: '#000', 
 
    strokeOpacity: 1.0, 
 
    strokeWeight: 3, 
 
    path: decodedPath 
 
    }); 
 
    var bounds = new google.maps.LatLngBounds(); 
 
    for (var i = 0; i < decodedPath.length; i++) { 
 
    bounds.extend(decodedPath[i]); 
 
    } 
 
    map.fitBounds(bounds); 
 

 

 
    poly.setMap(map); 
 
} 
 
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?libraries=geometry"></script> 
 
<div id="map_canvas"></div>