加载坐标时的距离误差

Range error when loading coordinates

本文关键字:距离 误差 坐标 加载      更新时间:2023-09-26

我有一个联系人页面,它从localstorage

获取坐标这样的

localStorage.getItem("jc")

我已经使用eval将字符串转换为变量

var thecoords = eval(localStorage.getItem("jc"));

并使用坐标以这些坐标为中心,例如

var center = new google.maps.LatLng(thecoords);并平移到该位置

map.panTo(center);

但是我得到这个错误

Uncaught RangeError: Maximum call stack size exceeded

我检查了我的坐标,它们的顺序是正确的lat,lng

google.maps.LatLng构造函数接受两个数字作为参数,而不是你传递给它的任何数字:

var center = new google.maps.LatLng(thecoords); // and pan'ed to that location

使用google.maps.LatLngLiteral对象的示例。

概念验证

代码片段:(来自jsfiddle,由于沙箱而无法实际工作)

localStorage.setItem('jc', JSON.stringify({lat: 40.7127837, lng: -74.0059413}));
function initialize() {
    var map = new google.maps.Map(
    document.getElementById("map_canvas"), {
        center: new google.maps.LatLng(37.4419, -122.1419),
        zoom: 13,
        mapTypeId: google.maps.MapTypeId.ROADMAP
    });
    console.log(localStorage.getItem('jc'));
    console.log()
    var marker = new google.maps.Marker({
      map: map,
      position: JSON.parse(localStorage.getItem('jc'))
    });
    map.panTo(JSON.parse(localStorage.getItem('jc')));
}
google.maps.event.addDomListener(window, "load", initialize);
html, body, #map_canvas {
    height: 100%;
    width: 100%;
    margin: 0px;
    padding: 0px
}
<script src="https://maps.googleapis.com/maps/api/js"></script>
<input id="clear" value="clear store" type="button" onclick="clearLocalStorage()" />
<div id="panel">
            <div id="color-palette"></div>
        </div>
<div id="map_canvas" style="width:750px; height:450px; border: 2px solid #3872ac;"></div>

不,您不需要使用eval()。存储在本地存储器中的项已经是一个变量。根本不要使用邪恶的eval()。

首先通过控制台记录坐标,并将其与Google Maps API文档进行比较。