AngularJs- TypeError:无法读取未定义的属性“纬度”

时间:2016-05-10 10:26:02

标签: html angularjs google-maps google-maps-api-3 google-maps-markers

我想在我的页面中显示带有可拖动标记的Google地图。这是我的代码:

header.php:

gone

map.js:

<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?v=3&sensor=true"></script>

map.html:

    app.directive('mapDirective',function(){
    return {
        templateUrl: 'map.html',
        restrict: 'EA',
        require: '?ngModel',
        scope:{
            myModel: '=ngModel'
        },
        link: function(scope , element, attrs , ngModel){
            var mapOptions;
            var googleMap;
            var searchMarker;
            var searchLatLng;
            scope.searchLocation = {
                latitude: 48.137273,
                longitude: 11.575251
            };
            ngModel.$render = function(){
                console.log("hhh");
                searchLatLng = new google.maps.LatLng(scope.myModel.latitude, scope.myModel.longitude);

                mapOptions = {
                    center: searchLatLng,
                    zoom: 12,
                    mapTypeId: google.maps.MapTypeId.ROADMAP
                };

                googleMap = new google.maps.Map(element[0],mapOptions);

                searchMarker = new google.maps.Marker({
                    position: searchLatLng,
                    map: googleMap,
                    draggable: true
                });

                google.maps.event.addListener(searchMarker, 'dragend', function(){
                    scope.$apply(function(){
                        scope.myModel.latitude = searchMarker.getPosition().lat();
                        scope.myModel.longitude = searchMarker.getPosition().lng();
                    });
                }.bind(this));

            };

            scope.$watch('myModel', function(value){
                var myPosition = new google.maps.LatLng(scope.myModel.latitude, scope.myModel.longitude);
                searchMarker.setPosition(myPosition);
            }, true);
        }
    }
});

的index.html:

<div>
    <div style="display: block; height: 200px; width: 100%; ">
    </div>
</div>

实际上,我收到了这个错误:

<map-directive ng-model="testModel"></map-directive>

如何解决?

编辑: 我更改了 maps.js

TypeError: Cannot read property 'latitude' of undefined

但它没有改变。

1 个答案:

答案 0 :(得分:0)

myModel变量应包含纬度和经度值。应该从

设置

<map-directive ng-model="testModel"></map-directive>

您需要在控制器中创建如下对象,并将此对象指定为指令,如上面的html。

var testModel = {
    latitude:1.2323,
    longitude:2.3434
};