微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

HTML5地理定位watchPosition只调用一次

我正在使用html 5创建一个 Android应用程序,我想在用户移动时从用户访问latlong.我使用过watchPostion,但它只是一次我的用户位置.
var watchID;
var geoLoc;

function showLocation(position) {
  var latitude = position.coords.latitude;
  var longitude = position.coords.longitude;

    var ll=new google.maps.LatLng(latitude,longitude);
    map.setCenter(ll);

  console.log("Latitude : " + latitude + " Longitude: " + longitude);
}

function errorHandler(err) {
  if(err.code == 1) {
    console.log("Error: Access is denied!");
  }else if( err.code == 2) {
    console.log("Error: Position is unavailable!");
  }
    }
    if(navigator.geolocation){
      // timeout at 60000 milliseconds (60 seconds)
      var options = {timeout:60000};
      geoLoc = navigator.geolocation;
      watchID = geoLoc.watchPosition(showLocation,errorHandler,options);


   }else{
      console.log("Sorry,browser does not support geolocation!");
   }

解决方法

几个月前我一直在做类似的事情.我记得有同样的问题.也许这会有所帮助.
$(document).ready(function(){  
    initLocationProcedure();
}

function initLocationProcedure() {
    map = new google.maps.Map(document.getElementById('map_canvas'),{
          zoom : 17
    });

    if (navigator.geolocation) {
        navigator.geolocation.getCurrentPosition(displayAndWatch,locError,{
            enableHighAccuracy : true,timeout : 60000,maximumAge : 0
        });
    } else {
        alert("Your phone does not support the Geolocation API");
    }
}

function displayAndWatch(position) {
    // set current position
    setUserLocation(position);
    // watch position
    watchCurrentPosition();
}

function setUserLocation(pos) {
    // marker for userLocation
    userLocation = new google.maps.Marker({
           map : map,position : new google.maps.LatLng(pos.coords.latitude,pos.coords.longitude),title : "You are here",icon : "../img/user-location.svg",// scroll to userLocation
    map.panTo(new google.maps.LatLng(pos.coords.latitude,pos.coords.longitude));
});

这是你在寻找的

function watchCurrentPosition() {
    var positionTimer = navigator.geolocation.watchPosition(function(position) {
        setMarkerPosition(userLocation,position);
        map.panTo(new google.maps.LatLng(position.coords.latitude,position.coords.longitude));
    });
}

function setMarkerPosition(marker,position) {
     marker.setPosition(new google.maps.LatLng(position.coords.latitude,position.coords.longitude));
     console.log(position);
}

小提琴
http://jsfiddle.net/XEFks/

原文地址:https://www.jb51.cc/html5/168484.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。