Javascript 在angularjs应用程序中使用Google API显示多边形

Javascript 在angularjs应用程序中使用Google API显示多边形,javascript,html,angularjs,google-maps,Javascript,Html,Angularjs,Google Maps,我想这样做:显示地图,让用户画一个多边形,编辑它和/或清除它。问题是我使用的是angular,但即使如此,我还是希望使用与示例相同的代码。我现在面临的问题是地图没有显示 这些是我在index.html中包含的内容: <script src="bower_components/jquery/dist/jquery.min.js"></script> <script src="bower_components/bootstrap/dist/js/bootstrap.mi

我想这样做:显示地图,让用户画一个多边形,编辑它和/或清除它。问题是我使用的是angular,但即使如此,我还是希望使用与示例相同的代码。我现在面临的问题是地图没有显示

这些是我在
index.html
中包含的内容:

<script src="bower_components/jquery/dist/jquery.min.js"></script>
<script src="bower_components/bootstrap/dist/js/bootstrap.min.js"></script>

<script
        src="https://maps.googleapis.com/maps/api/js?key=MY_API_KEY&libraries=drawing">
</script>


<script src="bower_components/angular/angular.js"></script>
<script src="bower_components/angular-route/angular-route.js"></script>
                <section id="placeholder">
                    <div id="map" ></div>
                </section>
我得到了这个错误:

jquery.min.js:2 jQuery.Deferred exception: Cannot read property 'firstChild' of null TypeError: Cannot read property 'firstChild' of null
    at Object._.vg (https://maps.googleapis.com/maps/api/js?key=MY_API_KEY&libraries=drawing:87:391)
at new Ag (https://maps.googleapis.com/maps/api/js?key=MY_API_KEY&libraries=drawing:89:76)
    at HTMLDocument.<anonymous> 
    at j (http://localhost:8080/bower_components/jquery/dist/jquery.min.js:2:29999)
    at k (http://localhost:8080/bower_components/jquery/dist/jquery.min.js:2:30313)
jquery.min.js:2 jquery.延迟异常:无法读取null类型的属性“firstChild”错误:无法读取null类型的属性“firstChild”
在对象处(https://maps.googleapis.com/maps/api/js?key=MY_API_KEY&libraries=drawing:87:391)
在新公司(https://maps.googleapis.com/maps/api/js?key=MY_API_KEY&libraries=drawing:89:76)
在HTMLDocument。
在j(http://localhost:8080/bower_components/jquery/dist/jquery.min.js:2:29999)
在k(http://localhost:8080/bower_components/jquery/dist/jquery.min.js:2:30313)
错误:

TypeError:无法读取null的属性“firstChild”

通常发生的原因是映射容器(
)在映射初始化后尚未就绪或无法找到

对于第一个场景,您可以利用
google.maps.event.addDomListener(窗口'load',initMap)
确保在DOM就绪后初始化映射

范例

angular.module('myApp',[])
.controller('MapCtrl',['$scope',
职能($范围){
$scope.initMap=函数(){
var center=new google.maps.LatLng(-33.870501151.206704);
变量映射选项={
缩放:12,
中心:中心,,
mapTypeId:google.maps.mapTypeId.TERRAIN
};
$scope.map=new google.maps.map(document.getElementById('map'),mapOptions);
};
google.maps.event.addDomListener(窗口'load',$scope.initMap);
}]);
#地图{
高度:240px;
}

您省略了角度代码。如果不查看map div的确切位置以及GoogleMap初始化的时间点,就很难确定到底出了什么问题

我最明智的猜测是,从错误消息来看,这很可能是在加载div之前尝试初始化map的问题

初始化映射的代码很可能是在上述元素位于DOM中之后执行的

由于您使用的是AngularJS,映射可能会在控制器内初始化。我不能肯定没有看到应用程序结构等


此外,请确保为地图指定高度和宽度

如果我在angular控制器中使用jQuery代码,它会工作吗?@Llg,当然会