我的 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>
当我运行这段代码时。我在 Firebug 中收到这条消息。 google.maps.LatLng 不是构造函数
怎么了?我该如何解决这个问题?
最佳答案
当您的代码继续执行时,Google Maps API javascript 会异步加载。然后,您的代码会在 Maps API 可用之前使用它。
要等待 Maps API,您可以将 ko.applyBindings 调用包装在 jQuery onload 事件处理程序中
$(window).load(function() {
ko.applyBindings(addCiniViewModel, document.getElementById("AddCiniForm"));
});
以下是 Google 提供的另一个示例,介绍如何在初始化使用 map API 的代码之前等待 map API:https://developers.google.com/maps/documentation/javascript/tutorial
关于javascript - 使用 KnockoutJS 添加 Google map ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20718183/