使用KnockoutJS添加Google地图

时间:2013-12-21 10:49:28

标签: javascript google-maps knockout.js

我在html文件中有以下部分。

<script src="http://maps.googleapis.com/maps/api/js?key=AIzaSyDwsTgxJyu7KG7BPM3q54mgjSHl1imLnCM&sensor=false">
</script>
<script type="text/javascript">
    $(function () {
        require(["Work/AddCiniViewModel"], function (model) {
            addCiniViewModel = new model();
            addCiniViewModel.createMap();
            ko.applyBindings(addCiniViewModel, document.getElementById("AddCiniForm"));
            }
        });

我在ViewModel文件中有以下部分。

 self.map;
        self.Lng = ko.observable(12.24);
        self.Lat = ko.observable(24.54);

        self.createMap = function () {
            var elevator;
            var myOptions = {
                zoom: 3,
                center: new google.maps.LatLng(12.24, 24.54),
                mapTypeId: 'terrain'
            };
            map = new google.maps.Map($('#map')[0], myOptions);
        }


        ko.bindingHandlers.map = {
            init: function (element, valueAccessor, allBindingsAccessor, addCiniViewModel) {


                var position = new google.maps.LatLng(allBindingsAccessor().latitude(),
                    allBindingsAccessor().longitude());

                var marker = new google.maps.Marker({
                    map: allBindingsAccessor().map,
                    position: position,
                    title: name
                });

                self._mapMarker = marker;
            },
            update: function (element, valueAccessor, allBindingsAccessor, addCiniViewModel) {
                var latlng = new google.maps.LatLng(allBindingsAccessor().latitude(), allBindingsAccessor().longitude());
                self._mapMarker.setPosition(latlng);

            }
        };

我想在下面的div中看到谷歌地图及其纬度值。

<div id="map"></div>
            <input data-bind="value: Lat" />
            <input data-bind="value: Lng" />
            <div data-bind=" style: style:{width:'300px',height:'300px'}, 
                latitude: addCiniViewModel.Lat, longitude:addCiniViewModel.Lng, map:map">
            </div>

当我运行此代码时。我在萤火虫中得到了这个消息。 google.maps.LatLng不是构造函数

怎么了?我该如何解决这个问题?

1 个答案:

答案 0 :(得分:0)

Google Maps API javascript正在异步加载,而代码的执行仍在继续。然后,您的代码会在Maps API可用之前使用它。

要等待Maps API,您可以将ko.applyBindings调用包装在jQuery onload事件处理程序中

$(window).load(function() {
    ko.applyBindings(addCiniViewModel, document.getElementById("AddCiniForm"));
});

以下是Google在初始化使用它的代码之前如何等待地图API的另一个示例:https://developers.google.com/maps/documentation/javascript/tutorial