我正在尝试学习传单库并尝试缩放到单击的功能。可能是一个简单的问题,但我对js和传单很新。 我已经看到了如何执行此操作的示例,例如此帖How to zoom on marker click event in Mapbox Leaflet? 但我不认为这个例子是从ajax调用获取数据,因此在这里不起作用?
function callback (response) {
quake = L.geoJson(response,
{
onEachFeature: function (feature, layer)
{
layer.bindPopup( "Mag: " + String(feature.properties.mag));
}
}).addTo(map);
map.fitBounds(quake.getBounds());
};
quake.on('click', function(e) {
map.setView([e.latlng], 12)
});
我也试过这个,但是它输出了一个没有定义标记的错误。但是如果我理解正确的话,L.geoJson会默认创建标记并将它们保存为“震动”,因为我上面的示例目前无效。
marker.on('click', function(e) {
map.setView([e.latlng], 12)
});
以下是我的codepen codepen example
的完整链接我希望有人能指出我正确的方向
答案 0 :(得分:1)
非常接近。您只需将click处理程序添加到onEachFeature函数即可。
我在下面创建了一个工作片段...
var map = L.map('map').setView([36.235412, -95.800781], 2);
var earthquake = document.querySelector(".earth");
earthquake.addEventListener("click", getQuake);
L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
maxZoom: 19,
attribution: '© <a href="http://www.openstreetmap.org/copyright">OpenStreetMap</a>'
}).addTo(map);
// Create an empty geoJSON layer to be filled later by button click
var quake = L.geoJSON().addTo(map);
function getQuake (){
$.ajax(
{
url:"https://earthquake.usgs.gov/earthquakes/feed/v1.0/summary/2.5_day.geojson",
dataType : 'json',
jsonCallback : 'getJson',
success : callback
}
)
};
function callback (response) {
quake = L.geoJson(response,
{
onEachFeature: function (feature, layer)
{
layer.bindPopup( "Mag: " + String(feature.properties.mag));
layer.on('click', function (e) {
map.setView(e.latlng, 12)
});
}
}).addTo(map);
map.fitBounds(quake.getBounds());
};
#map {
height: 350px;
width: 650px;
margin:auto;
}
#earthquake{
margin-left: 420px;
margin-bottom: 10px;
}
#about {
text-align: center;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/leaflet/1.2.0/leaflet.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/leaflet/1.2.0/leaflet.css" rel="stylesheet"/>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Leaflet Demo</title>
</head>
<body>
<div id="about">
<h1>Leaflet Map Demo Template</h1>
<p>Data from dayly M2.5+ Earthquakes <em><strong>https://earthquake.usgs.gov</em></strong></p>
</div>
<div id="earthquake">
<button class="earth">Add Earthquake data</button></id>
</div>
<div id="map"></div>
</body>
</html>