设置leaflet.js地图以显示当前位置

Ste*_*e C 3 javascript undefined leaflet meteor

我正在使用leaf的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);
Run Code Online (Sandbox Code Playgroud)

我不断得到的错误是

Uncaught TypeError: Cannot read property 'addLayer' of undefined
L.Marker.L.Class.extend.addTo @ leaflet-src.js:3511
(anonymous function) @ client.js?ea76789cca0ff64d5985320ec2127d5de1fb802f:28
Run Code Online (Sandbox Code Playgroud)

当我在console.log(latit)或console.log(longit)时,它返回数字,以及之后的"undefined".提前感谢任何可以帮助您的人!

编辑:

初始渲染时的确切控制台输出:

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
Run Code Online (Sandbox Code Playgroud)

编辑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);
      }
    }
  }
}
});
};
Run Code Online (Sandbox Code Playgroud)

Ste*_*e C 10

谢谢,@ sosdoc,初始化这些变量确实有帮助,并将在我的项目的长期帮助我.但是为了简单地在我当前的位置渲染地图,我找到了一个更简单的答案!leaflet内置了一个locate方法.而不是通过'未初始化'latit和longit vars,我这样做:

map = L.map('map', {doubleClickZoom: false}).locate({setView: true, maxZoom: 16});
Run Code Online (Sandbox Code Playgroud)

它将地图设置为您的位置.maxzoom只是您可以缩放并可以更改的次数的变量.


Sos*_*doc 2

从完整代码可以看出错误就在这里

map = L.map('map', {
  doubleClickZoom: false
}).setView([latit, longit], 13); 
Run Code Online (Sandbox Code Playgroud)

因为latitlongit没有设置(在 JS 中,它们是未定义的,直到你给它们任何值)。

您可能会感到困惑,因为此代码在您定义的任何回调之前执行:Template.map.rendered在此脚本终止后执行。

解决这个问题的方法是为这些参数设置一个初始值

var latit = 0;
var longit = 0;
Run Code Online (Sandbox Code Playgroud)

您的地图最初将以非洲西部为中心。

然后,在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));
} 
Run Code Online (Sandbox Code Playgroud)

如果需要,您还可以将标记的位置传递给函数panTo()

map.panTo(abc.getLatLng());
Run Code Online (Sandbox Code Playgroud)

最后,请记住,每当您将 a 传递function()给其他函数(稍后将执行该函数以响应某个事件)时,这在 JavaScript 中已广泛完成。