嗨,我是谷歌地图Api的新手,我在谷歌地图中创建了多边形,我想知道我点击了哪个多边形,我试过但我无法找到,这是我的代码
function initialize() {
var mapOptions = {
zoom: 14,
center: new google.maps.LatLng(12.9648451,77.5741997),
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
var arr = new Array();
var polygons = [];
var bounds = new google.maps.LatLngBounds();
var coordinates = [];
// downloadUrl("subdivision-coordinates.php", function(data) {
var xmlString = '<subdivisions><subdivision name="Auburn Hills"><coord lat="12.973111130721453" lng="77.54373550415039"/><coord lat="12.929112653428087" lng="77.53360748291016"/><coord lat="12.936306851970127" lng="77.57635116577148"/></subdivision><subdivision name="Vanderveen"><coord lat="12.97227473026135" lng="77.59489059448242"/><coord lat="12.952200275819832" lng="77.58750915527344"/><coord lat="12.95487696326559" lng="77.60536193847656"/></subdivision></subdivisions>';
//var xmlString =$('#xml_values').val();
var xml = xmlParse(xmlString);
var subdivision = xml.getElementsByTagName("subdivision");
for (var i = 0; i < subdivision.length; i++) {
arr = [];
var coordinates = xml.documentElement.getElementsByTagName("subdivision")[i].getElementsByTagName("coord");
//console.log("coordinates="+xml.documentElement.getElementsByTagName("subdivision")[i].getElementsByTagName("coord"));
for (var j=0; j < coordinates.length; j++) {
arr.push(new google.maps.LatLng(
parseFloat(coordinates[j].getAttribute("lat")),
parseFloat(coordinates[j].getAttribute("lng"))
));
bounds.extend(arr[arr.length-1])
//console.log("arr lenghth="+arr.length+"___"+arr[arr.length-1]+"|___|"+coordinates[j])
}
polygons.push(new google.maps.Polygon({
paths: arr,
strokeColor: '#FF0000',
strokeOpacity: 0.8,
strokeWeight: 2,
fillColor: '#FF0000',
fillOpacity: 0.35
}));
polygons[polygons.length-1].setMap(map);
google.maps.event.addListener(polygons[polygons.length-1], 'click', function (event) {
alert(JSON.stringify(event));
});
}
map.fitBounds(bounds);
function xmlParse(str) {
if (typeof ActiveXObject != 'undefined' && typeof GetObject != 'undefined') {
var doc = new ActiveXObject('Microsoft.XMLDOM');
doc.loadXML(str);
return doc;
}
if (typeof DOMParser != 'undefined') {
return (new DOMParser()).parseFromString(str, 'text/xml');
}
return createElement('div', null);
}
}
google.maps.event.addDomListener(window, 'load', initialize);
如何识别使用google maps api
中的多边形数字点击哪个多边形答案 0 :(得分:1)
创建多边形时,添加一个附加属性以标识多边形,例如
polygons.push(new google.maps.Polygon({
id: i,
paths: arr,
strokeColor: '#FF0000',
strokeOpacity: 0.8,
strokeWeight: 2,
fillColor: '#FF0000',
fillOpacity: 0.35
}));
然后在您的事件监听器中,您应该能够从该多边形的this
范围获取此信息:
polygons[polygons.length-1].addListener('click', function (event) {
console.log(this.id);
});