我到目前为止的代码是使用Google Maps API接收用户输入的内容,在地图上查找,然后将他们输入的搜索附加到地图右侧。我缺少的一部分是,对于右侧的搜索,我必须使它们能够被点击,并且在点击时它们会转到地图上的标记。我想知道是否有人有任何建议或提示来帮助我弄清楚,因为我尝试了很多不同的东西(出于某种原因使用.on('click',...)将无法正常工作)。
谢谢! .html文件:
<!DOCTYPE html>
<html>
<head>
<title>Simple Map</title>
<script src="https://code.jquery.com/jquery-3.2.1.js"></script>
<script src = "project2.js"></script>
<link rel = "stylesheet" type = "text/css" href = "project2.css">
<meta name="viewport" content="initial-scale=1.0">
<meta charset="utf-8">
</head>
<body>
<form>
<div>
<label> Address: </label>
<input id = "address" type = "text">
<input id = "submit" type = "button" value = "Add">
<br><br>
</div>
</form>
<section>
<ul>
</ul>
</section>
<div id="map"></div>
<script async defer src="https://maps.googleapis.com/maps/api/js?key=AIzaSyAGysAFeYIRV2qqMeEcnehH9igIaSYxvvs&callback=initMap"></script>
</body>
</html>
.js文件:
function initMap() {
map = new google.maps.Map(document.getElementById('map'), {
center: {lat: 41.083, lng: -74.174},
zoom: 8
});
var geocoder = new google.maps.Geocoder();
document.getElementById('submit').addEventListener('click', function() {
showAddress(geocoder, map);
//getLinks();
});
}
function showAddress(geocoder, newMap)
{
var address = document.getElementById('address').value;
//console.log(address);
$('<li/>').addClass('list').text(address).appendTo('ul');
geocoder.geocode({'address': address}, function(results, status) {
if (status === 'OK') {
newMap.setCenter(results[0].geometry.location);
var marker = new google.maps.Marker({
map:newMap,
position: results[0].geometry.location
});
}
else {
alert('Geocode was not successful for reason: ' + status);
}
});
}
/*
function getLinks()
{
console.log("hey");
$('#elements').on('click', 'li', function(){
alert($(this).text());
console.log("hey2");
});
}*/
.css文件:
input[type = text]
{
width: 375px;
}
li {
list-style-type: none;
width: 450px;
border-style: solid;
padding: 0.3em;
margin-left: 475px;
margin-right: auto;
margin-bottom: .5em;
}
.list {
background-color: #8E8989;
}
#map {
position:absolute;
top: 50px;
height:60%;
width:40%;
/* Always set the map height explicitly to define the size of the div
* element that contains the map. */
}
html, body{
height: 100%;
margin:0;
padding:5px;
}
谢谢!
答案 0 :(得分:0)
我建议在id
添加<ul>
,并为其添加click
事件监听器,而不是动态创建的<li>
。
例如:
<ul id="address-list">
然后在javascript中,使用:
$("#address-list").on("click",".list",function(){
/* Do something */
})
答案 1 :(得分:0)
要在动态生成的元素上添加事件,您需要使用类似
的内容$('body').on('click', 'li', function() { // do something });