在这个最新版本中,XML 文件
<countries>
<country name="USA" lat="40.0" lng="-100.0" width="30.0"/>
<country name="France" lat="46.6" lng="2.7" width="10"/>
<country name="Germany" lat="51.1" lng="10.1" width="20"/>
</countries>
地图图块完成加载后立即加载。getProjection
如果我不等待瓷砖加载完成,我将无法正确调用。文档指出,获取投影需要初始化地图,并建议收听projection_changed
. 两种方式都有效,但我仍然觉得听 tiles_loaded 更安全,如果 xml 加载出现问题,如果地图被缩放或平移了相当大的数量,它将再次被调用。
var map;
var xmlLoaded = false;
function initialize() {
var mapOptions = { center: new google.maps.LatLng(30.0, 0.0), zoom: 2,
mapTypeId: google.maps.MapTypeId.ROADMAP };
map = new google.maps.Map(document.getElementById("map_canvas"), mapOptions);
google.maps.event.addListener(map, 'tilesloaded', loadData);
}
function loadData() {
if(!xmlLoaded) {
$.ajax({
type: "GET",
url: "co2data.xml",
dataType: "xml",
success: function(xml) {
var countries = xml.documentElement.getElementsByTagName("country");
for(var i = 0, country; country = countries[i]; i++) {
var name = country.getAttribute("name");
var lat = parseFloat(country.getAttribute("lat"));
var lng = parseFloat(country.getAttribute("lng"));
var point = map.getProjection().fromLatLngToPoint(new google.maps.LatLng(lat,lng));
// width is really an arbitrary unit, relative to CO2 tonnage.
// equals the side of the drawn square.
// it is measured in google maps points units.
var width = parseFloat(country.getAttribute("width"));
makeCO2Rect(name, point, width);
}
xmlLoaded = true;
}
});
}
}
矩形由以点为单位的宽度定义(整个世界是 256x256 点),因此在将它们的中心分配给更传统的 LatLng 时需要进行一些转换。
function rectParamsToBounds(point, width) {
var ctrX = point.x;
var ctrY = point.y;
var swX = ctrX - (width/2);
var swY = ctrY - (width/2);
var neX = ctrX + (width/2);
var neY = ctrY + (width/2);
return new google.maps.LatLngBounds(
map.getProjection().fromPointToLatLng(new google.maps.Point(swX, swY)),
map.getProjection().fromPointToLatLng(new google.maps.Point(neX, neY)));
}
最后,创建一个矩形,其国家名称进入MarkerWithLabel(在此处使用 v1.1.5,您可以热链接到http://google-maps-utility-library-v3.googlecode.com/svn/tags/markerwithlabel/ 1.1.5/src/markerwithlabel_packed.js虽然我更喜欢保存本地副本)
由于拖动矩形似乎是不可能的,因此其中心的标记用作手柄。当它被拖动时,相关的矩形会随之移动。
function makeCO2Rect(name, point, width) {
var rect = new google.maps.Rectangle({
map: map,
bounds: rectParamsToBounds(point, width)
});
var marker = new MarkerWithLabel({
map: map,
position: map.getProjection().fromPointToLatLng(new google.maps.Point(point.x, point.y)),
draggable: true,
raiseOnDrag: false,
labelContent: name,
labelAnchor: new google.maps.Point(30, 0),
labelClass: "labels", // the CSS class for the label
labelStyle: {opacity: 1.0}
});
google.maps.event.addListener(marker, 'drag', function(event) {
var newLatLng = event.latLng;
var newPoint = map.getProjection().fromLatLngToPoint(newLatLng);
rect.setBounds(rectParamsToBounds(newPoint, width));
});
}
google.maps.event.addDomListener(window, 'load', initialize);
标签的样式需要在 .labels CSS 类和构造函数中完成,矩形有描边颜色、粗细、不透明度和填充颜色等选项。