Javascript - 保存地理位置坐标

标签 javascript html local-storage

我如何将坐标保存在本地存储中,以便它不应该每次都询问用户是否允许 GPS 或位置以及清除本地存储值的按钮,以便它可以再次请求坐标?

仅供引用: 我正在使用Praytimes JS显示穆斯林祈祷时间,但对于每个位置,我必须手动添加该位置的纬度和经度。

下面是我的代码:

<script type="text/javascript" src="https://maps.google.com/maps/api/js?sensor=false"></script>
<script type="text/javascript"> 
  var x = document.getElementById("currentlocation");

  var geocoder;

  if (navigator.geolocation) {
    navigator.geolocation.getCurrentPosition(successFunction, errorFunction);
} 
//Get the latitude and the longitude;
function successFunction(position) {
    var lat = position.coords.latitude;
    var lng = position.coords.longitude;
    codeLatLng(lat, lng)
}

function errorFunction(){
    $('#currentlocation').html("Geocoder failed");
}

  function initialize() {
    geocoder = new google.maps.Geocoder();



  }

  function codeLatLng(lat, lng) {

    var latlng = new google.maps.LatLng(lat, lng);
    geocoder.geocode({'latLng': latlng}, function(results, status) {
      if (status == google.maps.GeocoderStatus.OK) {
      console.log(results)
        if (results[1]) {
         //formatted address
         $('#currentlocation').html(results[0].formatted_address);
        //find country name
             for (var i=0; i<results[0].address_components.length; i++) {
            for (var b=0;b<results[0].address_components[i].types.length;b++) {

            //there are different types that might hold a city admin_area_lvl_1 usually does in come cases looking for sublocality type will be more appropriate
                if (results[0].address_components[i].types[b] == "administrative_area_level_2") {
                    //this is the object you are looking for
                    city= results[0].address_components[i];
                    break;
                }
            }
        }
        //city data
        $('#currentlocation').html(city.short_name + " " + city.long_name)


        } else {
          $('#currentlocation').html("No results found");
        }
      } else {
        $('#currentlocation').html("Geocoder failed due to: " + status);
      }
    });
  }
</script>

<p id="currentlocation"></p>

<script type="text/javascript" src="http://praytimes.org/code/v2/js/PrayTimes.js"></script>    

<script type="text/javascript">
    function loadTable(position) {
        prayTimes.setMethod('MWL'); 
        var date = new Date(); // today
        var times = prayTimes.getTimes(date, [position.coords.latitude, position.coords.longitude]);
        var list = ['Fajr', 'Sunrise', 'Dhuhr', 'Asr', 'Maghrib', 'Isha', 'Midnight'];

        var html = '<table id="timetable">';
        html += '<tr><th colspan="2">'+ date.toLocaleDateString()+ '</th></tr>';
        for(var i in list)  {
            html += '<tr><td>'+ list[i]+ '</td>';
            html += '<td>'+ times[list[i].toLowerCase()]+ '</td></tr>';
        }
        html += '</table>';
        document.getElementById('table').innerHTML = html;
    }

    if (navigator.geolocation) {
        navigator.geolocation.getCurrentPosition(loadTable);
    }
</script> 

最佳答案

用坐标信息定义一个对象:

var coordinatesObject = 
{
  lat: position.coords.latitude,
  lng: position.coords.longitude
}

保存到本地存储:

localStorage.setItem('coordinates', 
JSON.stringify(coordinatesObject));

获取它:

let objFromLocalStorage = 
localStorage.getItem('coordinates');

关于Javascript - 保存地理位置坐标,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51229922/

相关文章:

javascript - Socket.configure Undefined is not a function 错误

javascript - Dojo:在单页应用程序中交换两个不同的 View

javascript - JQuery $(window).resize() 函数无法正常工作

reactjs - 如何存储到本地存储? ( react )

javascript - 要更改的本地存储

javascript - 在 IE10 中拒绝访问本地存储

javascript - 在MySQL中选择多行的前十个条目

asp.net - 如何可靠地从自定义实体的 OnSave 事件保存 ASP.NET IFRAME?

javascript - 开 Jest 模拟一个 ES6 类以供正在测试的类使用

html - IE 9 中的 Rapheal 饼图渲染问题