我试图从一个从文件加载的geojson数据中显示3个字段属性。数据加载并添加到地图中。标记/点显示在HTML页面上。 BUt然后我点击标记/点没有任何反应。大约.setLngLat(features.geometry.coordinates)
我得到 ReferenceError: features is not defined
我不确定我错过了什么或者需要做什么才能使其适用于当前范围。
我非常感谢您解决此问题的任何提示或技巧。
{% load static %}
<!DOCTYPE html>
<html>
<head>
<meta charset='utf-8'/>
<title></title>
<meta name='viewport' content='initial-scale=1,maximum-scale=1,user-scalable=no'/>
<script src='https://api.tiles.mapbox.com/mapbox-gl-js/v0.37.0/mapbox-gl.js'></script>
<link href='https://api.tiles.mapbox.com/mapbox-gl-js/v0.37.0/mapbox-gl.css' rel='stylesheet'/>
<style>
body {
margin: 0;
padding: 0;
}
#map {
position: absolute;
top: 0;
bottom: 0;
width: 100%;
}
</style>
</head>
<body>
<div id='map'></div>
<script>
mapboxgl.accessToken = 'pk.myaccesstoken';
var map = new mapboxgl.Map({
container: 'map',
style: 'mapbox://styles/mapbox/streets-v9',
center: [10.600, 55.900],
zoom: 6.0,
hash: true
});
map.on('load', function () {
// Add a layer showing the places.
map.addSource('markers', {
type: 'geojson',
data: '{% static 'json/architecture_map.geojson'%}'
});
map.addLayer({
"id": "places",
"source": "markers",
"type": "circle",
"paint": {
"circle-radius": 5,
"circle-color": "#fb05ff"
}
});
map.on('click', function (e) {
var f = map.queryRenderedFeatures(e.point, {layers: ['places']});
if (f.length) {
var feature = f[0];
new mapboxgl.Popup()
.setLngLat(features.geometry.coordinates)
.setHTML(ProjectPopup(feature))
.addTo(map);
}
});
function ProjectPopup(feature){
var html = '';
html += "<div>";
html += "<h2>" + feature.properties.project + "</h2>";
html += "<p>" + feature.properties.image + "</p>";
html += "<a>" + feature.properties.slug + "</a>";
html += "</div>";
return html;
}
// Change the cursor to a pointer when the mouse is over the places layer.
map.on('mouseenter', 'places', function () {
map.getCanvas().style.cursor = 'pointer';
});
// Change it back to a pointer when it leaves.
map.on('mouseleave', 'places', function () {
map.getCanvas().style.cursor = '';
});
});
</script>
</body>
</html>
geojson文件的示例。
{
"type": "FeatureCollection",
"crs": {
"type": "name",
"properties": {
"name": "EPSG:4326"
}
},
"features": [
{
"type": "Feature",
"properties": {
"image": "project01.JPG",
"project": "Project Title",
"slug": "project-title"
},
"geometry": {
"type": "Point",
"coordinates": [
9.932241438432886,
57.04649628721196
]
}
}
]
}
答案 0 :(得分:0)
首先,您提供的geojson不是有效的。您可以在此处查看地理位置:http://geojsonlint.com/
第二个你的&#34;未定义&#34;错误可能只是一个错字。你定义了你的变量:
var feature = f[0];
但是使用是这样的:
new mapboxgl.Popup()
.setLngLat(features.geometry.coordinates)
.setHTML(ProjectPopup(feature))
.addTo(map);
}
&#13;
您注意到features
与您定义的名为feature
的变量不同,因此导致未定义。
我纠正了你的错误。看这里: https://jsfiddle.net/andi_lo/xzrzzzsc