我尝试获取两个位置,使用 Google Maps API 中的 directionsService.route
查找两点之间的路线,然后将返回的路线对象存储在 localStorage 中以供稍后使用使用。我正在尝试使用下面的解决方案(对于一个有点不相关的问题),但它在最后两行失败,因为 .extend()
、.getNorthEast()
和.getSouthWest()
存储在 Google 对象的原型(prototype)中。这些方法有助于在组合多个行程时设置新 map 的边界。
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()
转换时,我尝试了多种解决方法来保存原型(prototype)函数,但没有任何效果。
更新
我尝试使用这个add-on帮助保留原型(prototype)函数,它确实如此,但我认为不可能在序列化/反序列化后将这些函数重新添加回 JS 对象,因为该对象已经是 initialized
var serializer = new ONEGEEK.GSerializer();
var s = serializer.serialize(result.routes[0].bounds);
var d = serializer.deserialize(s);
我最终做的是一个有点黑客的解决方法来模仿需要一些原型(prototype)函数的 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作为参数创建一个新的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);
关于javascript - 使用 JSON.stringify 时将原型(prototype)函数添加回返回的 Google Maps API 对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35464037/