设置feflet.js地图以显示用户的当前位置
我正在使用 leaflet.js 包进行流星工作,在初始渲染时无法让地图默认为我的当前位置。setView 方法可以很好地处理硬数字,但它不喜欢我的变量。我对 js 还很陌生,所以错误可能很明显。这是我的:
Template.map.rendered = function() {
L.Icon.Default.imagePath = 'packages/bevanhunt_leaflet/images';
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
console.log('--- Your Position: ---');
console.log('Lat: ' + position.coords.latitude);
latit = position.coords.latitude;
console.log('Long: ' + position.coords.longitude);
longit = position.coords.longitude;
console.log('---------------------');
var abc = L.marker([position.coords.latitude, position.coords.longitude]).addTo(map);
}
)}
map = L.map('map', {
doubleClickZoom: false
}).setView([latit, longit], 13);
我不断收到的错误是
Uncaught TypeError: Cannot read property 'addLayer' of undefined
L.Marker.L.Class.extend.addTo @ leaflet-src.js:3511
(anonymous function) @ client.js?ea76789cca0ff64d5985320ec2127d5de1fb802f:28
当我 console.log(latit) 或 console.log(longit) 时,它会返回数字,以及后面的“未定义”。在此先感谢任何能提供帮助的人!
编辑:
初始渲染时的精确控制台输出:
Exception from Tracker afterFlush function:
debug.js:41 ReferenceError: latit is not defined
at Template.map.rendered (client.js? ea76789cca0ff64d5985320ec2127d5de1fb802f:36)
at template.js:116
at Function.Template._withTemplateInstanceFunc (template.js:437)
at fireCallbacks (template.js:112)
at null.<anonymous> (template.js:205)
at view.js:104
at Object.Blaze._withCurrentView (view.js:523)
at view.js:103
at Object.Tracker._runFlush (tracker.js:468)
at onGlobalMessage (setimmediate.js:102)
client.js?ea76789cca0ff64d5985320ec2127d5de1fb802f:22 --- Your Position: ---
client.js?ea76789cca0ff64d5985320ec2127d5de1fb802f:23 Lat: 41.0525926
client.js?ea76789cca0ff64d5985320ec2127d5de1fb802f:25 Long: -73.5398427
client.js?ea76789cca0ff64d5985320ec2127d5de1fb802f:27 ---------------------
leaflet-src.js:3511 Uncaught TypeError: Cannot read property 'addLayer' of undefinedL.Marker.L.Class.extend.addTo @ leaflet-src.js:3511(anonymous function) @ client.js?ea76789cca0ff64d5985320ec2127d5de1fb802f:28
编辑 2: 我想保持简单,但这是我的完整 js:
var map;
var latit;
var longit;
// on startup run resizing event
Meteor.startup(function() {
$(window).resize(function() {
$('#map').css('height', window.innerHeight - 82 - 45);
});
$(window).resize(); // trigger resize event
});
// create marker collection
var Markers = new Meteor.Collection('markers');
Meteor.subscribe('markers');
Template.map.rendered = function() {
L.Icon.Default.imagePath = 'packages/bevanhunt_leaflet/images';
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
console.log('--- Your Position: ---');
console.log('Lat: ' + position.coords.latitude);
latit = position.coords.latitude;
console.log('Long: ' + position.coords.longitude);
longit = position.coords.longitude;
console.log('---------------------');
var abc = L.marker([position.coords.latitude, position.coords.longitude]).addTo(map);
}
)}
map = L.map('map', {
doubleClickZoom: false
}).setView([latit, longit], 13); //Error is somewhere before here!!
L.tileLayer.provider('Thunderforest.Outdoors').addTo(map);
map.on('dblclick', function(event) {
Markers.insert({latlng: event.latlng});
});
//add markers
var query = Markers.find();
query.observe({
added: function (document) {
var marker = L.marker(document.latlng).addTo(map)
.on('click', function(event) {
map.removeLayer(marker);
Markers.remove({_id: document._id});
});
},
//remove markers
removed: function (oldDocument) {
layers = map._layers;
var key, val;
for (key in layers) {
val = layers[key];
if (val._latlng) {
if (val._latlng.lat === oldDocument.latlng.lat && val._latlng.lng === oldDocument.latlng.lng) {
map.removeLayer(val);
}
}
}
}
});
};
谢谢,@sosdoc,初始化这些变量确实有帮助,并且会对我项目的长期发展有所帮助。但是为了简单地在我当前位置渲染地图,我发现了一个更简单的答案!leaflet 内置了一个定位方法。我没有传递“未初始化”的纬度和经度变量,而是这样做了:
map = L.map('map', {doubleClickZoom: false}).locate({setView: true, maxZoom: 16});
它将地图设置为您的位置。maxzoom 只是一个变量,表示您可以缩放的次数,可以更改。
从完整代码中,你可以看到错误在这里
map = L.map('map', {
doubleClickZoom: false
}).setView([latit, longit], 13);
因为
latit
和
longit
未设置(在 JS 中,它们是未定义的,直到你给它们任何值)。
你可能会感到困惑,因为这段代码在你定义的任何回调之前执行:
Template.map.rendered
在此脚本终止后执行。
解决这个问题的方法是设置这些参数的初始值
var latit = 0;
var longit = 0;
你的地图最初将以非洲西部为中心。
然后,在执行
map.rendered
时,你需要将地图重新​​定位到更新后的 latit 和 longit 变量(更新它们不会更新地图)。
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
latit = position.coords.latitude;
longit = position.coords.longitude;
// this is just a marker placed in that position
var abc = L.marker([position.coords.latitude, position.coords.longitude]).addTo(map);
// move the map to have the location in its center
map.panTo(new L.LatLng(latit, longit));
}
如果你想,您还可以将标记的位置传递给
panTo()
函数:
map.panTo(abc.getLatLng());
最后,请记住,每当您将
function()
传递给某个其他函数时,该函数都会在稍后响应某个事件时执行,这在 JavaScript 中已广泛完成。
navigator.geolocation.getCurrentPosition(function(location) {
var latlng = new L.LatLng(location.coords.latitude, location.coords.longitude);
alert(latlng);
var mymap = L.map('mapid').setView(latlng, 13)
L.tileLayer('https://api.tiles.mapbox.com/v4/{id}/{z}/{x}/{y}.png?access_token={accessToken}', {
attribution: 'Map data © <a href="http://openstreetmap.org">OpenStreetMap</a> contributors, <a href="http://creativecommons.org/licenses/by-sa/2.0/">CC-BY-SA</a>, Imagery © <a href="https://mapbox.com">Mapbox</a>',
maxZoom: 18,
id: 'mapbox.streets',
accessToken: 'pk.eyJ1IjoiYmJyb29rMTU0IiwiYSI6ImNpcXN3dnJrdDAwMGNmd250bjhvZXpnbWsifQ.Nf9Zkfchos577IanoKMoYQ'
}).addTo(mymap);
var marker = L.marker(latlng).addTo(mymap);
});
#mapid {
height: 500px;
}
<script src="https://d3js.org/d3.v3.min.js"></script>
<script src="https://d3js.org/topojson.v0.min.js"></script>
<link rel="stylesheet" href="https://npmcdn.com/[email protected]/dist/leaflet.css" />
<script src="https://npmcdn.com/[email protected]/dist/leaflet.js"></script>
<div id="mapid"></div>
//可参考进一步的传单教程