Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/471.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
将名称空间添加到javascript_Javascript_Google Maps_Google Maps Api 3_Javascript Namespaces - Fatal编程技术网

将名称空间添加到javascript

将名称空间添加到javascript,javascript,google-maps,google-maps-api-3,javascript-namespaces,Javascript,Google Maps,Google Maps Api 3,Javascript Namespaces,几年前,我曾在谷歌地图api上工作,并编写了一个可重用的小实用程序。当时添加GoogleMapAPI引用确实会在页面的全局命名空间中添加所有api类。因为这是工作样本 <script src="http://maps.google.com/maps?SOMEPARAMETERS"> <script> var map= new GMap2(document.getElementById("map_canvas")); var point= new LatLng(31,75)

几年前,我曾在谷歌地图api上工作,并编写了一个可重用的小实用程序。当时添加GoogleMapAPI引用确实会在页面的全局命名空间中添加所有api类。因为这是工作样本

<script src="http://maps.google.com/maps?SOMEPARAMETERS">
<script>
var map= new GMap2(document.getElementById("map_canvas"));
var point= new LatLng(31,75);
var line= new Polyline(OPTIONS);
</script>

var map=newgmap2(document.getElementById(“map_canvas”);
var点=新车床(31,75);
变量线=新多段线(选项);
在v3中,所有Google Maps JavaScript API代码都存储在Google.Maps.*命名空间中,而不是全局命名空间中。作为此过程的一部分,大多数对象也已重命名,并且还进行了一些更改

现在您必须按如下方式编写上述代码

<script src="APIURL">
<script>
var map= new google.map.Map(document.getElementById("map_canvas"));
var point= new google.mapLatLng(31,75);
var line= new google.map.Polyline(OPTIONS);
</script>

var map=new google.map.map(document.getElementById(“map_canvas”);
var point=new google.mapLatLng(31,75);
var line=新的google.map.Polyline(选项);
问题


我在GoogleV2 API时代写了一个库,在许多项目中使用过,效果很好。但现在我正在做一个新项目,使用GoogleV3API,并希望重用旧的v2库。但是添加v3库不会在全局命名空间中添加API类,我的库也不起作用。我们有没有办法像在C#on top中那样将名称空间添加到JavaScript文件中,这样我们就可以编写类而无需附加名称空间

您可能只需要使用引用:

(function() { // A scoping function to avoid creating glboals
    var GMap2 = google.map.Map;
    var LatLng = google.map.LatLng;
    var Polyline = googlemap.Polyline;


    // ...your code using the above here...
})();
不过,这是假设参数没有改变

或者,您可以使用Facade模式:

function GMap2(/*...relevant args...*/)

    return new google.map.Map(/*...relevant args here, possibly modified...*/);
}
(其他人也是如此。)


(即使您将
new
GMap2
一起使用,这也有效,因为
new
表达式的结果将是您在返回对象时从构造函数返回的对象。)

maps API的第三个版本使用不同的方法和新方法名称,因此,即使您可以这样命名您的javascript(您不能),您也必须更改所有名称、参数等以匹配新的API,因此您最好只是重写您的库。