获取decodepath谷歌地图的中心

时间:2016-03-06 16:41:06

标签: google-maps dictionary center

我一直在寻找...... 我有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);

1 个答案:

答案 0 :(得分: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

代码段:&#39;

&#13;
&#13;
var geocoder;
var map;
var mapid = "aq|rFttwdQiizCfl}AqcbFfxv@_jfBff}@silAdfdDl`UzrlCmpp@z~eBgq@rrz`@~_dK?rfBstgK~daE~eBbwDulch@";
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);
&#13;
html,
body,
#map_canvas {
  height: 100%;
  width: 100%;
  margin: 0px;
  padding: 0px
}
&#13;
<script src="https://maps.googleapis.com/maps/api/js?libraries=geometry"></script>
<div id="map_canvas"></div>
&#13;
&#13;
&#13;