如何动态地从下面的坐标集计算地图中心坐标。这些坐标来自xml文件。根据XML坐标,我想设置中心坐标。 var triangleCoords = [ new google.maps.LatLng(51.049042161127545,-3.1417465209960938), new google.maps.LatLng(51.00477555656173,-3.1235504150390625), new google.maps.LatLng(51.01428024457833,-3.0490493774414062), new google.maps.LatLng(51.047962990786715,-3.0806350708007812) ];
<html>
<head>
<link href="/maps/documentation/javascript/examples/default.css" rel="stylesheet">
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false"></script>
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"></script>
<script>
function initialize() {
var myLatLng = new google.maps.LatLng(51.017303, -3.096289);
var mapOptions = {
zoom: 12,
center: myLatLng,
mapTypeId: google.maps.MapTypeId.TERRAIN
};
var bermudaTriangle;
var map = new google.maps.Map(document.getElementById('map-canvas'),
mapOptions);
var triangleCoords = [
new google.maps.LatLng(51.049042161127545, -3.1417465209960938),
new google.maps.LatLng(51.00477555656173, -3.1235504150390625),
new google.maps.LatLng(51.01428024457833, -3.0490493774414062),
new google.maps.LatLng(51.047962990786715, -3.0806350708007812)
];
// Construct the polygon
bermudaTriangle = new google.maps.Polygon({
paths: triangleCoords,
strokeColor: '#FF0000',
strokeOpacity: 0.8,
strokeWeight: 2,
fillColor: '#FF0000',
fillOpacity: 0.35
});
bermudaTriangle.setMap(map);
/// To display Marker within the above drawn polygon coordinates
var pos = new google.maps.LatLng(51.01428024457833, -3.0490493774414062);
var marker = new google.maps.Marker({
position: pos,
map: map,
title: name
});
var info = "This is a marker for the following co-ordinates:<br />latitude: " + latitude + "<br/>longitude: " + longitude;
google.maps.event.addListener(marker, 'click', function () {
var infowindow = new google.maps.InfoWindow({
content: info
});
infowindow.open(map, marker);
});
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
</head>
<body>
<div id="map-canvas" style="height: 500px; width: 500px">
</div>
</body>
</html>
Could you please help me out this.
答案 0 :(得分:1)
您必须添加名为map.setBounds
的方法
首先,您声明一个新的LatLngBounds
,然后添加您拥有的所有latlng。
像这样:
var bounds = new google.maps.LatLngBounds();
for (var i = 0; i < triangleCoords.length; i++) {
bounds.extend(triangleCoords[i]);
}
map.fitBounds(bounds);
有关https://developers.google.com/maps/documentation/javascript/reference#Map
的更多信息