我正在尝试从google.maps.Map对象扩展我的原型函数。但我得到的是不能读取未定义的属性'firstChild'。
基本上我只是想添加一个自定义原型对象,它也是google.maps.Map的一个实例。下面是我的代码
<script src="https://maps.googleapis.com/maps/api/js?key=MY_KEY&callback=initMap&libraries=drawing" async defer></script>
function Map(id, options) {
this.id = id;
this.latlng = options.center;
}
Map.prototype = new google.maps.Map;
function initMap()
{
map = new Map('map', mapOptions);
}
所以我喜欢的是当我运行'new Map('map',mapOptions)'这将创建一个新的google.maps.Map();实例,这将呈现一个地图。但是我不确定我在这里缺少什么因为我在javascript中使用原型相当新。希望你能帮助我。感谢
答案 0 :(得分:1)
您现在遇到的错误是因为脚本标记上的async和defer属性,请查看此处http://peter.sh/experiments/asynchronous-and-deferred-javascript-execution-explained/
评论后更新&#34;我尝试删除异步和延迟,但新错误无法找到&#39; firstchild&#39;&#34;
以下代码段仅适用于w3schools尝试编辑器,因为谷歌地图API密钥。
更新以使用继承
<!DOCTYPE html>
<html>
<body>
<h1>My First Google Map</h1>
<div id="googleMap" style="width:100%;height:400px;"></div>
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyBu-916DdpKAjTmJNIgngS6HL_kDIKU0aU"></script>
<script>
function Map(id, options) {
var element = document.getElementById(id);
// Call constructor of superclass to initialize superclass-derived members.
google.maps.Map.call(this, element, options);
this.id = id;
this.latlng = options.center;
this.customAddMarkerAtCenter = function(){
return new google.maps.Marker({
position: this.latlng,
map: map,
title: 'Hello World!'
});
}
}
Map.prototype = Object.create(google.maps.Map.prototype);
Map.prototype.constructor = Map;
function initMap()
{
map = new Map( "googleMap" , {
center:new google.maps.LatLng(51.508742,-0.120850),
zoom:5
}, "mapId");
map.customAddMarkerAtCenter();
var marker = new google.maps.Marker({
position: new google.maps.LatLng(50.508742,-0.120850),
map: map,
title: 'Hello World!'
});
alert(map.id )
alert(map.latlng )
}
initMap();
</script>
<!--
To use this code on your website, get a free API key from Google.
Read more at: https://www.w3schools.com/graphics/google_maps_basic.asp
-->
</body>
</html>
&#13;