0

別の関数からユーザージオロケーションナビゲーター関数をトリガーする方法を探しています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);
}
4

1 に答える 1

1

何をしようとしているのかわかりませんが、「getCurrentPosition」を呼び出すときに渡す最初の引数は、取得された位置で呼び出されるメソッドです。コメントで述べたように、 getCurrentPosition は常にすぐに返されますが、ユーザーの位置を取得できる場合はコールバック メソッドが呼び出されます (呼び出されない場合があります)。

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

最初にいくつかのデフォルト座標を使用してリーフレット マップを作成し、次にコールバック メソッドに提供された座標を使用してマップを再センタリングする必要があります。

于 2012-08-14T03:01:05.570 に答える