我对JavaScript还是很陌生,并且正在使用JS Leaflet进行分配。我应该在地图上映射用户以及一系列特征(多边形),并向后者添加弹出窗口。在弹出窗口中,指定了一些信息,包括从用户到要素的距离。 我应该使用模块显示模式来解决这个问题。
因此,我已经能够解决映射问题,但是由于用户位置无法正确更新,因此我无法计算用户与要素之间的距离。我使用了应该在locate函数中更新的全局变量,但是由于某种原因更新没有按预期进行。
感觉好像我缺少与javascript行为/揭示模块模式有关的基本知识,但我不确定它是什么。 感谢所有帮助,代码如下:
var mapApp = (function() {
var foos = {
type: "FeatureCollection",
features: [
{
type: "Feature",
properties: {
title: "title",
description: "desc",
logo: "img.png",
distance: 0
},
geometry: {
type: "Polygon",
coordinates: [
[
[13.192812502384186, 55.7029732524422],
[13.192858099937439, 55.7029732524422],
[13.192858099937439, 55.70300045726667],
[13.192812502384186, 55.70300045726667],
[13.192812502384186, 55.7029732524422]
]
]
}
}
]
};
var map = L.map("map", {
center: [55.70293, 13.192945],
zoom: 18
});
var myPosition = L.marker(map._lastCenter);
function init() {
L.tileLayer(
"https://api.tiles.mapbox.com/v4/{id}/{z}/{x}/{y}.png?access_token={accessToken}",
{
attribution:
'Map data © <a href="https://www.openstreetmap.org/">OpenStreetMap</a> contributors, <a href="https://creativecommons.org/licenses/by-sa/2.0/">CC-BY-SA</a>, Imagery © <a href="https://www.mapbox.com/">Mapbox</a>',
maxZoom: 19,
id: "mapbox.streets"
}
).addTo(map);
addFeatures();
locateUser();
}
function locateUser() {
var myPositionIcon = L.icon({
iconUrl: "icon.png",
iconSize: [32, 32]
});
map
.locate({
setView: false,
enableHighAccuracy: true,
watch: false,
maxZoom: 13
})
.on("locationfound", function myPositionFound(e) {
//displaying my location on the map with icon if position found
// updating global variable myPosition
myPosition = L.marker(e.latlng, {
icon: myPositionIcon
}).addTo(map);
console.log("User position: ", myPosition.getLatLng()); //my position coordinates are ok in the console, but myPosition doesn't get updated
calculateDistances(myPosition.getLatLng());
})
.on("locationerror", function myPositionNotFound() {
alert("Could not retrieve user location");
});
}
//add features
function addFeatures() {
L.geoJSON(foos, {
onEachFeature: addPopup
}).addTo(map);
}
function addPopup(currentFeature, layer) {
currentFeature.properties.distance = Math.round(
calcDistance(myPosition.getLatLng(), currentFeature)
);
layer.bindPopup(
"<img src=" +
currentFeature.properties.logo +
" alt=" +
currentFeature.properties.title +
"height='50' width='50'>" +
"<h2>" +
currentFeature.properties.title +
"</h2>" +
"<h4>" +
currentFeature.properties.description +
"</h4>" +
"<h4>Avstånd: " +
currentFeature.properties.distance +
" m.</h4>"
);
}
function calcDistance(position, feature) {
//getting the lat and lng of the feature coordinates - choose the corner with index 2 of the polygon
var standCoord = L.latLng(
feature.geometry.coordinates[0][2][1],
feature.geometry.coordinates[0][2][0]
);
return position.distanceTo(standCoord);
}
return {
init: init
};
})();
mapApp.init();