这是我第一次使用javascript google maps api,当我尝试LatLngBounds.extend()
时,我一直收到此错误
Uncaught TypeError: a.lat is not a function
我已经能够获得并平均所有坐标并将相机移动到该位置,但我希望能够动态调整缩放以适应所有内容。当我在for循环中注释掉行bounds.extend(myLatLng)
时,我没有收到错误。
map = new google.maps.Map(document.getElementById('map'), {
center: {lat: -34.397, lng: 150.644},
zoom: 8
});
var avLat = 0;
var avLon = 0;
var pathCoords = [];
var bounds = new google.maps.LatLngBounds();
for (var i = 0, len = data.length; i < len; i++) {
var myLatLng = {lat: parseFloat(data[i].Lat), lng: parseFloat(data[i].Lon)};
pathCoords.push(myLatLng);
bounds.extend(myLatLng);
avLat += parseFloat(data[i].Lat);
avLon += parseFloat(data[i].Lon);
}
var path = new google.maps.Polyline({
path: pathCoords,
geodesic: true,
strokeColor: '#0000FF',
strokeOpacity: 1.0,
strokeWeight: 2
});
path.setMap(map);
avLat = avLat/data.length;
avLon = avLon/data.length;
map.fitBounds(bounds);
// map.setCenter({lat: avLat, lng: avLon});
// map.setZoom(12);
}
答案 0 :(得分:3)
您无法在google.maps.LatLngLiteral
方法中使用google.maps.LatLngBounds.extend
,您必须将其转换为google.maps.LatLng
对象(至少目前为止)。
代码段
var geocoder;
var map;
var data = [{
Lat: -34.397,
Lon: 150.644
}, {
Lat: -34,
Lon: 150
}];
function initialize() {
map = new google.maps.Map(document.getElementById('map'), {
center: {
lat: -34.397,
lng: 150.644
},
zoom: 8
});
var avLat = 0;
var avLon = 0;
var pathCoords = [];
var bounds = new google.maps.LatLngBounds();
for (var i = 0, len = data.length; i < len; i++) {
var myLatLng = new google.maps.LatLng(parseFloat(data[i].Lat), parseFloat(data[i].Lon));
pathCoords.push(myLatLng);
bounds.extend(myLatLng);
avLat += parseFloat(data[i].Lat);
avLon += parseFloat(data[i].Lon);
}
var path = new google.maps.Polyline({
path: pathCoords,
geodesic: true,
strokeColor: '#0000FF',
strokeOpacity: 1.0,
strokeWeight: 2
});
path.setMap(map);
avLat = avLat / data.length;
avLon = avLon / data.length;
map.fitBounds(bounds);
}
google.maps.event.addDomListener(window, "load", initialize);
&#13;
html,
body,
#map {
height: 100%;
width: 100%;
margin: 0px;
padding: 0px
}
&#13;
<script src="https://maps.googleapis.com/maps/api/js"></script>
<div id="map"></div>
&#13;