使用 JSON.stringify 时将原型函数添加回返回的 Google Maps API 对象

Adding prototype functions back to returned Google Maps API object when using JSON.stringify

本文关键字:返回 Google Maps 对象 API 添加 stringify JSON 函数 原型 使用      更新时间:2023-09-26

我尝试获取两个位置,在Google Maps API中使用directionsService.route查找两点之间的方向,然后将返回的方向对象存储在localStorage中以供以后使用。我正在尝试使用以下解决方案(针对一个不相关的问题(,但它在最后两行失败,因为.extend().getNorthEast().getSouthWest() 存储在 Google 对象的原型中。这些方法有助于在组合多个行程时设置新地图的边界。

https://lemonharpy.wordpress.com/2011/12/15/working-around-8-waypoint-limit-in-google-maps-directions-api/

if (count == 0) {
    combinedResults = unsortedResults[key].result;
} else {
    // only building up legs, overview_path, and bounds in my consolidated object. This is not a complete 
    // directionResults object, but enough to draw a path on the map, which is all I need
    combinedResults.routes[0].legs = combinedResults.routes[0].legs.concat(unsortedResults[key].result.routes[0].legs);
    combinedResults.routes[0].overview_path = combinedResults.routes[0].overview_path.concat(unsortedResults[key].result.routes[0].overview_path);
    combinedResults.routes[0].bounds = combinedResults.routes[0].bounds.extend(unsortedResults[key].result.routes[0].bounds.getNorthEast());
    combinedResults.routes[0].bounds = combinedResults.routes[0].bounds.extend(unsortedResults[key].result.routes[0].bounds.getSouthWest());
}

当您运行JSON.stringify()JSON.parse()转换时,我已经尝试了几种解决方法来保存原型函数,但没有任何效果。

更新

我尝试使用此附加组件来帮助保留原型函数,它确实如此,但我认为在序列化/反序列化后无法将这些功能重新添加到 JS 对象中,因为该对象已经初始化

var serializer = new ONEGEEK.GSerializer();
var s = serializer.serialize(result.routes[0].bounds);
var d = serializer.deserialize(s);

我最终做的是一个黑客变通办法,以模仿需要一些原型函数的bounds.extend()函数(如下(。此解决方案的唯一问题是,如果我需要与缓存的对象进行交互以进行其他任何操作,我将处于相同的位置

var existing = combinedResults.routes[0].bounds;
var adding = trip2.routes[0].bounds;
existing.north = existing.north > adding.north ? existing.north : adding.north;  
existing.south = existing.south < adding.south ? existing.south : adding.south;  
existing.east = existing.east > adding.east ? existing.east : adding.east;
existing.west = existing.west < adding.west ? existing.west : adding.west; 
基本上根本不

可能在 JSON 中存储函数。

要恢复原始LatLngBounds,您只需使用存储的 LatLngBoundsLiteral 作为参数来创建new LatLngBounds():例如

var json=JSON.parse(//stored string
                    '{"bounds:{"south":41.9029,"west":2.3,"north":55.7,"east":37.6}}');
json.bounds=new google.maps.LatLngBounds(json.bounds);