我有一些div,每个data-id都有一个特定的地址。 然后,我尝试从单击的div中获取data-id值,并在de geocode上进行设置,以将地图放在地址的中心。 但是我不知道如何在点击时制作它。
到目前为止,我的代码:
<div class="map">
<div class="btn_mapa" id="1" data-id="San Diego, CA"></div>
<div class="btn_mapa" id="2" data-id="Belo Horizonte, MG"></div>
<div class="btn_mapa" id="3" data-id="New York, NY"></div>
<!–– ... many others ... ––>
<div class="btn_mapa" id="259" data-id="Atlanta, GA"></div>
<div id="map-canvas" style="width: 100%; height: 100%;"></div>
</div>
<script src="https://maps.googleapis.com/maps/api/js?key=MYAPI"></script>
<script>
var geocoder;
var map;
var div1 = document.getElementById("1");
var address = div1.getAttribute("data-id");
function initialize() {
geocoder = new google.maps.Geocoder();
var latlng = new google.maps.LatLng(-34.397, 150.644);
var myOptions = {
zoom: 8,
center: latlng,
mapTypeControl: true,
mapTypeControlOptions: {
style: google.maps.MapTypeControlStyle.DROPDOWN_MENU
},
navigationControl: true,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById("map-canvas"), myOptions);
if (geocoder) {
geocoder.geocode({
address: address
}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
if (status != google.maps.GeocoderStatus.ZERO_RESULTS) {
map.setCenter(results[0].geometry.location);
} else {
alert("No results found");
}
} else {
alert("Geocode was not successful for the following reason: " + status);
}
});
}
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
答案 0 :(得分:1)
将点击侦听器添加到类<div>
的所有btn_mapa
中,在该点击侦听器功能(this
是对被点击的<div>
的引用)中,获取data-id
的{{1}}属性并对其进行地理编码:
<div>
}
代码段:
var btn_mapa = document.getElementsByClassName('btn_mapa');
for (var i=0; i<btn_mapa.length; i++) {
google.maps.event.addDomListener(btn_mapa[i], 'click', function() {
var address = this.getAttribute('data-id');
console.log(address);
geocodeAddress(address);
});
}
function geocodeAddress(address) {
if (geocoder) {
geocoder.geocode({
address: address
}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
if (status != google.maps.GeocoderStatus.ZERO_RESULTS) {
map.setCenter(results[0].geometry.location);
} else {
alert("No results found");
}
} else {
alert("Geocode was not successful for the following reason: " + status);
}
});
}
#map-canvas {
height: 80%;
}
html,
body {
height: 100%;
margin: 0;
padding: 0;
}
答案 1 :(得分:0)
我没有测试这段代码,但是它应该可以正常工作。试一试。
<div class="btn_mapa" id="1" data-id="San Diego, CA" onclick='handleClick(this);'></div>
<script>
function handleClick(element) {
console.log(element.getAttribute('data-id');
}
</scrip>