我有一个带有JSON多边形数组的谷歌地图。我需要在加载地图后将多边形居中。我对这部分遇到了麻烦。 PLS。有人来帮助我。
这是我的样本JSON
[{"ZoneID":7,"Name":"Testing Site Zone","Type":"Home","TypeID":0,"Perimeter":"25.774252,-80.190262 18.466465,-66.11829 32.321384,-64.75737","CellIds":"","Location":"","Company":"Company Co. Ltd.","CompanyID":0,"Color":"#598527","Image":null,"ImageFill":null,"Tag":null,"TagID":null,"CreatedDate":"2015-05-04T08:24:25.297345","LastModified":"2015-05-04T08:24:25.297345","Created_UserID":0,"Modified_UserID":0,"Created_User":"","Modified_User":"","ErrorMessage":null}]
这是加载JAVASCRIPT
var geocoder;
var perimeter = obj.Perimeter;
var name = obj.Name;
var type = obj.Type;
var company = obj.Company;
var address = obj.Location;
var color = obj.Color;
var map;
var polygon;
var pathCoordinates = new google.maps.MVCArray();
function initialize() {
geocoder = new google.maps.Geocoder();
map = new google.maps.Map(document.getElementById('map'), {
zoom: 10,
center: new google.maps.LatLng(13.7500, 100.4833),
mapTypeId: google.maps.MapTypeId.ROADMAP,
disableDefaultUI: true,
zoomControl: true
});
var parsePerimeter = perimeter.replace(/\),/g, "");
var coords = parsePerimeter.split(" ");
var recoords;
for (var k = 0; k < coords.length; k++) {
recoords = coords[k].split(",");
pathCoordinates.push(new google.maps.LatLng(parseFloat(recoords[0]), parseFloat(recoords[1])));
}
polygon = new google.maps.Polygon({
path: pathCoordinates,
strokeColor: color,
strokeOpacity: 0.8,
strokeWeight: 3,
fillColor: color,
fillOpacity: 0.35,
Company: company,
Name: name,
Address: address,
map: map
});
pathCoordinates = [];
polygon.setMap(map);
// Add a listener for the click event.
google.maps.event.addListener(polygon, 'click', showArrays);
infoWindow = new google.maps.InfoWindow();
google.maps.event.addListener(polygon, 'click', (function (polygon, k) {
return function () {
map.panTo(this.position);
}
})(polygon, k));
}
答案 0 :(得分:2)
由于Polygon没有getBounds
或getCenter
方法,您必须自己完成。
这里的关键是创建一个LatLngBounds
对象并使用每个多边形点对其进行扩展。然后,您可以将此对象与地图fitBounds
方法一起使用。
var polygon = new google.maps.Polygon({
path: path,
map: map
});
var bounds = new google.maps.LatLngBounds();
for (var i=0; i<polygon.getPath().length; i++) {
var point = new google.maps.LatLng(path[i].lat(), path[i].lng());
bounds.extend(point);
}
map.fitBounds(bounds);