Javascript和HTML5地理位置-如何存储位置

Javascript and HTML5 Geolocation - how to store the position?

本文关键字:存储 位置 何存储 HTML5 地理位置 Javascript      更新时间:2023-09-26

我正在使用HTML5地理定位api获取用户的位置,如下所示:

navigator.geolocation.getCurrentPosition(function (position) {
        loadWeather(position.coords.latitude + ',' + position.coords.longitude); //load weather using your lat/lng coordinates
  });
jQuery(document).ready(function() {
        loadWeather('Seattle',''); //@params location, woeid
});
function loadWeather(location, woeid) {
    jQuery.simpleWeather({
        location: location,
        woeid: woeid,
        unit: 'c',
        success: function(weather) {
        html = '<div class="weather_widget text-right"><h2><div class="icon_weather"><i class="icon-'+weather.code+'"></i></div><div class="degrees"><div class="temp_weather">'+weather.temp+'</div><div class="weather_deg">&deg;</div><div class="unit_weather">'+weather.units.temp+'</div></div></h2>';
        html += '<div class="city_weather">'+weather.city+'</div></div>';
       jQuery("#weather").html(html);
   },
   error: function(error) {
       jQuery("#weather").html('<p>'+error+'</p>');
  }
  });
}

这基本上加载了一个小部件,它根据地理位置显示天气。

现在我的问题是:

  1. 如何存储整个会话的位置变量?(这样它就不会在每次加载新页面时询问位置了?)

  2. 如何使整个网站都可以访问位置变量,以便在网站的其他功能中使用该位置?(比如谷歌地图)。

地理位置代码位于整个站点中包含的头文件中。

Hi您需要使用javaScript 的localStoragesessionStorage

要在本地存储中存储数据,请使用以下代码

localStorage.setItem('veriable_name','value');

要获得价值,请使用以下代码

localStorage.getItem('veriable_name');

要清除本地存储,请使用

localStorage.clear();

有关本地存储和会话存储的更多信息