You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用localStorage存储坐标后,无法获取纬度值的技术求助

问题解决:从localStorage获取纬度值失败的修复方案

你当前的问题出在读取localStorage的方式上:第一页是把包含lat和lng的对象转成JSON字符串,存入了coordinates这个键,但第二页错误地尝试通过coordinates.lat这个不存在的键直接取值,这显然拿不到数据。

正确的做法是先取出整个JSON字符串,再解析成JavaScript对象,之后才能访问lat属性,修改后的第二页代码如下:

window.onload = function () {
  // 先取出存储的JSON字符串
  const coordStr = localStorage.getItem('coordinates');
  // 解析成对象,同时处理可能未存储的情况
  const coordinates = coordStr ? JSON.parse(coordStr) : null;
  
  if (coordinates) {
    const lat = coordinates.lat;
    const IR = (-75 * lat) + 5025;
    const energie_pro = IR * 0.926 * 0.8 * 0.213 * 1.92 * 8;
    document.getElementById('eco_3000').innerText = energie_pro;
  } else {
    // 可以在这里处理未获取到坐标的情况,比如提示用户
    document.getElementById('eco_3000').innerText = '未获取到坐标信息';
  }
};

关键步骤说明

  • 用localStorage.getItem('coordinates')取出完整的JSON字符串,而不是不存在的coordinates.lat
  • 通过JSON.parse()将字符串还原为对象,这样就能正常访问lat属性
  • 添加了空值判断,避免因未存储坐标导致的代码报错

内容的提问来源于stack exchange,提问作者Rayane Lakhdar

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.20 07:48:11