地理位置无法返回确认

Geolocation can't return confirmation?

本文关键字:确认 返回 地理位置      更新时间:2023-09-26

我正在寻找一种从另一个函数mapInit()触发用户地理位置导航器功能的方法。它几乎有效,但我无法对getCurrentPosition()进行适当的回调来确认它进展顺利。它每次都返回未定义。

我的地理位置对象将不得不完成其他任务,所以我不希望它触发mapInit()。它应该必须获取用户位置,记录它并返回truefalse..有什么猜测吗?

谢谢:)

// Get user current position, return true or false
//
var geolocation = {
    get: function() {
        if (alert(navigator.geolocation.getCurrentPosition(this.success, this.error, {
            enableHighAccuracy: true,
            maximumAge: 5000
        })) {
            return true;
        } else {
            return false;
        }
    },
    success: function(position) {
        this.last = position; // record last position
        return true;
    },
    error: function() {
        alert('code: ' + error.code + 'n' + 'message: ' + error.message + 'n')
        return false;
    },
    last: undefined,
}
// Initialize leaflet map and get user location if coords are undefined
//
var mapInit = function(latitude, longitude) {
    if (!latitude && !longitude) { // if no latlng is specified, try to get user coords
        if (geolocation.get()) {
            latitude = geolocation.last.coords.latitude;
            longitude = geolocation.last.coords.longitude;
        } else {
            alert('oups!');
        }
    }
    var map = L.map('map').setView([latitude, longitude], 15);
    L.tileLayer('http://{s}.tile.cloudmade.com/#APIKEY#/68183/256/{z}/{x}/{y}.png', {
        minZoom: 13,
        maxZoom: 16,
    }).addTo(map);
    var marker = L.marker([latitude, longitude]).addTo(map);
}

不确定我是否理解您要做什么,但是当您调用"getCurrentPosition"时,您传递的第一个参数是一个方法,一旦检索到Position,该方法将调用。 正如您在评论中所说,getCurrentPosition 将始终立即返回,但如果可以检索用户位置(可能永远不会调用),则将调用回调方法:

navigator.geolocation.getCurrentPosition( function(position) {
  var lat = position.coords.latitude;
  var lon = position.coords.longitude;
  //do something like recent the Map
});

您需要先使用一些默认坐标创建传单映射,然后使用提供给回调方法的坐标将映射重新居中。