设置当前位置时,位置返回undefined

时间:2016-09-19 13:56:22

标签: javascript jquery

我正在使用谷歌地址自动完成api来预填充地址。我在会话中设置地理位置。这工作正常,但对于圆形对象的参数,"位置"我收到一个javascript错误,说位置未定义。我应该怎么解决这个问题?

function geolocate() {
  if (navigator.geolocation && !sessionStorage.geolocation) {
    navigator.geolocation.getCurrentPosition(function (position) {
      sessionStorage.geolocation = {
        lat: position.coords.latitude,
        lng: position.coords.longitude
      };
    });
  }
  var circle = new google.maps.Circle({
    center: sessionStorage.geolocation,
    radius: position.coords.accuracy
  });
  autocomplete.setBounds(circle.getBounds());
}

1 个答案:

答案 0 :(得分:0)

这实际上很容易。不知道为什么我以前没想过这个。首先.. sessionStorage只能存储字符串,我传递一个对象。所以1:这是不正确的。 2:位置不在var circle的范围内,因为它是回调函数的参数。解决方案是

function geolocate() {
  if (navigator.geolocation && !sessionStorage.geolocation) {
    sessionStorage.geolocation = true;
    navigator.geolocation.getCurrentPosition(function (position) {
      window.geolocation = {
        lat: position.coords.latitude,
        lng: position.coords.longitude
      };
      window.o = {
        center: window.geolocation,
        radius: position.coords.accuracy
      }
    });
  }
  var circle = new google.maps.Circle(window.o);
  autocomplete.setBounds(circle.getBounds());
}
相关问题