我有一个主页面使用ajax加载子页面,其中一个子页面包含一个谷歌地图,因此它使用<script>
标记加载谷歌地图api:
<script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&sensor=SET_TO_TRUE_OR_FALSE">
我注意到这会将一堆css和js文件加载到我的主页面和子页面中。当我点击主页面中的其他链接时,我希望能够卸载所有这些文件并删除所有创建的js对象,即清理所有内容并返回原始状态。有没有办法做到这一点?
答案 0 :(得分:3)
你的问题的答案实际上比你想象的要复杂一些。处理许多相关细节的一个好问题和一组答案位于:What is the Proper Way to Destroy a Map Instance?。
我不确定您的问题,但听起来您可能创建了一个多次加载Google Maps API的页面(或者可能,取决于用户的选择),您应该完全避免这种情况。 Google承认存在与重新加载地图相关的内存泄漏错误,并强烈建议不要进行多次地图重新加载。 Google本质上不支持多个地图加载用例。
查看上面问题链接中提供的一些信息;它包含一些很好的讨论和信息。
查看来自Google的Chris Broadfoot和Luke Mahe讨论的Google Maps API Office Hours May 9 2012 Video:他们不支持涉及重新加载地图的用例,API只打算加载一次,并且他们确认有一个内存泄漏错误。将播放设置为~12:50以查看有关销毁地图的部分,重新加载地图的问题以及它们为避免出现问题而提供的建议。首先,如果您必须隐藏然后显示地图,他们建议您重复使用单个地图实例。
答案 1 :(得分:3)
老问题..但这是我的解决方案:
// First getting rid of the google.maps object (to avoid memory leaks)
// Then, we are also removing google-maps related script tags we can identify.
// After unloaded, if maps is reloaded more than once on the same page;
// we'll also get a warning in the console saying: "Warning: you have included the
// Google Maps API multiple times on this page. This may cause unexpected errors."
// This script will also avoid that warning.
if (window.google !== undefined && google.maps !== undefined) {
delete google.maps;
$('script').each(function () {
if (this.src.indexOf('googleapis.com/maps') >= 0
|| this.src.indexOf('maps.gstatic.com') >= 0
|| this.src.indexOf('earthbuilder.googleapis.com') >= 0) {
// console.log('removed', this.src);
$(this).remove();
}
});
}
更新 :请注意,这不是一个完整的解决方案。可能存在复制/克隆/引用的对象。更好的方法是在iframe中对地图进行沙盒处理并从DOM中删除iframe。
答案 2 :(得分:1)
不是你想的那样。完成此操作的最简单方法是使用iframe
加载应用程序的“重”部分。然后当你摆脱iframe
时,你摆脱了与地图相关的CSS和JS。
在版本2中,Google Maps API进行了GUnload()
调用,但版本3 API没有此调用。