【发布时间】:2019-08-22 02:58:56
【问题描述】:
我有一些 div,每个 data-id 都有一个特定的地址。 然后我试图从单击的 div 中获取数据 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>
【问题讨论】:
-
使用
$(this).attr("data-id")或$(this).data("id"),attr("#data-id"))
标签: javascript google-maps google-geocoder google-geolocation