2

基本上我想在我的位置设置一个标记(使用 navigator.geolocation 检索)并在我移动时更新他的位置以使其显示我的真实位置。这是我的代码。

  var map;
  var marker;
  var newLatlng;
  var i = 0;

  //here i create a map centered on 0,0
  function initialize() {
    directionsDisplay = new google.maps.DirectionsRenderer();
    var chicago = new google.maps.LatLng(0,0);
    var mapOptions = {
      zoom: 6,
      mapTypeId: google.maps.MapTypeId.ROADMAP,
      center: chicago
    }
    map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
    directionsDisplay.setMap(map);

    updatePos();

  }


//here I set my marker (if i==0 -> first run)
function updatePos(){

var options = {
    timeout: 500000, enableHighAccuracy: true
};
var myUpdatedPos = navigator.geolocation.watchPosition(onSuccess, onError, options);

function onSuccess(position) {

    if (i==0){
        marker = new google.maps.Marker({
                        position: new google.maps.LatLng(position.coords.latitude, position.coords.longitude),
                        map: map,
                        animation: google.maps.Animation.DROP
                    });
    }
    i++;

    //here I update the position
    newLatlng = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
    marker.setPosition(newLatlng);
}

// onError Callback receives a PositionError object
//
    function onError(error) {
        alert('code: '    + error.code    + '\n' +
        'message: ' + error.message + '\n');
    }
}

这段代码可以工作,但更新我的位置有点慢,我认为是因为:

new google.maps.LatLng(position.coords.latitude, position.coords.longitude);

每次我的位置改变时都会调用它。但我不确定这个构造的真正作用。它是否会调用服务器并且必须等待应答?

有人对加快此代码有什么好的建议吗?

先感谢您!

4

1 回答 1

4

使用 watchPosition,您可以指定缓存位置的持续时间。尝试使用不太短也不太长的东西。

将更新位置的简单示例:

navigator.geolocation.getCurrentPosition(onSuccess, onError, { maximumAge: 3000, timeout: 5000, enableHighAccuracy: true });

参考:

http://docs.phonegap.com/en/2.5.0/cordova_geolocation_geolocation.md.html#geolocationOptions

于 2013-04-09T14:22:17.120 回答