从js函数中使用变量,并使用其他函数

时间:2016-06-12 06:29:11

标签: javascript android

我是JS的新手,我正在尝试使用PhoneGap构建一个Web应用程序,该应用程序从Android设备获取GPS坐标并在某些JS功能中使用它们,但我遇到了麻烦。我应该如何通过' lat'和' lon'在' coords'

中使用它们
In [8]: z
...
NameError: name 'z' is not defined

2 个答案:

答案 0 :(得分:1)

更改你的onSuccess()和initMap()。你的onSuccess将lat和lon设置为它的私有变量。此外,由于这些是异步调用,因此initMap最终可能无法获取所需的数据。这就是你的onSuccess()触发时需要initMap()的原因。

function onSuccess(position) {      
    var lat = position.coords.latitude;
    var lon = position.coords.longitude;
    initMap(lat, lon);
}

function initMap(lat, lon) {
  //your implementation
}

一旦你完成了这些,就不需要调用onSuccess,onError&你最后完成的initMap

答案 1 :(得分:0)

这是你需要的

var app = {
    // Application Constructor
    initialize: function() {
        this.bindEvents();
    },
    // Bind Event Listeners
    //
    // Bind any events that are required on startup. Common events are:
    // 'load', 'deviceready', 'offline', and 'online'.
    bindEvents: function() {
        document.addEventListener('deviceready', this.onDeviceReady, false);
    },
    // deviceready Event Handler
    //
    // The scope of 'this' is the event. In order to call the 'receivedEvent'
    // function, we must explicitly call 'app.receivedEvent(...);'
    onDeviceReady: function() {
       // app.receivedEvent('deviceready');
       navigator.geolocation.getCurrentPosition(app.onSuccess, app.onError);
    },

    onSuccess: function(position){
        var longitude = position.coords.longitude;
        var latitude = position.coords.latitude;
        var latLong = new google.maps.LatLng(latitude, longitude);

        var mapOptions = {
            center: latLong,
            zoom: 13,
            mapTypeId: google.maps.MapTypeId.ROADMAP
        };

        var map = new google.maps.Map(document.getElementById("map"), mapOptions);

        var marker = new google.maps.Marker({
              position: latLong,
              map: map,
              title: 'my location'
          });
    },

    onError: function(error){
        alert("the code is " + error.code + ". \n" + "message: " + error.message);
    },
};

app.initialize();