1

我对 Javascript 很陌生,遇到了一个我自己无法解决/理解的问题。

假设我使用“userPosition”属性创建了“UserMap”类,并希望使用 Geolocation API 获取坐标。

navigator.geolocation.getCurrentPosition(this.getCoordinates);

然后在回调函数中我得到纬度和经度:

var coords = { "lat" : position.coords.latitude, "lng" : position.coords.longitude };

我的问题是:我怎样才能让这个回调函数报告回 UserMap 实例,以便更新 userPosition 属性?显然this.userPosition = coords;在这里行不通。现在我对处理回调感到非常无助。我希望每次从用户那里获得更新的坐标时都不必制作新对象。

这是错误的代码:

    function UserMap() {
        this.map = L.map('map', {"zoomControl" : false});
        this.userPosition = {};
        this.boundary = {};

        if (navigator.geolocation){
            navigator.geolocation.getCurrentPosition(this.getCoordinates);
        }
        else{ alert("Geolocation is not supported by your browser.");
            return false;
        }
        this.map.on("click", function(e) {
            alert("Lat: " + e.latlng.lat + " Lng: " + e.latlng.lng);
        });
        this.display();
    }

    UserMap.prototype.getCoordinates = function(position) {
        var coords = { "lat" : position.coords.latitude, "lng" : position.coords.longitude};
        this.userPosition = coords; // I understand why this line won't work, but can't find a workaround solution
    }

    UserMap.prototype.display = function() {
        var lat = this.userPosition.lat;
        var lng = this.userPosition.lng;
        this.map.setView([lat, lng], 18);
        var tile = L.tileLayer('http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
        attribution: '&copy; <a href="http://osm.org/copyright">OpenStreetMap</a> contributors',
            minZoom: '16',
        }).addTo(this.map);
        L.marker([lat, lng]).addTo(this.map)
            .bindPopup('You are here!')
            .openPopup();
    }
4

2 回答 2

0

您可以使用 map.locate 函数和 locationfound 事件来完成此操作:检查此小提琴:http: //jsfiddle.net/tuchi35/3fTL7/1/并检查定位文档: http: //leafletjs.com/reference .html#map-locate

基本上,我删除了您的 getCoordinates 函数并将其替换为对定位函数的调用和“locationfound”事件的事件处理程序:

map.locate({setView:true}); map.on('locationfound', function (data){ L.marker(map.getCenter).addTo(map) .bindPopup('You are here!') .openPopup(); });

希望能帮助到你

于 2013-12-12T16:10:50.987 回答
0

在回调中,您可以使用 ajax 调用,它将以非阻塞方式与服务器交互。

如果您使用 jquery,您可以执行以下操作:

 $.ajax({
   url: "test.html",
   data: coords
})
.done(function() {
  alert("done")
});
于 2013-12-10T01:27:40.137 回答