谷歌地图和淘汰赛 [英] Google maps and knockoutjs
问题描述
我正在制作一个单页应用程序,我需要在第二个视图中显示 Google 地图.我正在使用要创建地图对象的 Google 地图 API.
var map = new google.maps.Map(mapId, {变焦:5,中心:新的 google.maps.LatLng(55, 11),mapTypeId: google.maps.MapTypeId.ROADMAP});
参数 mapId
给我带来了问题.该视图包含一个 ID 为mapId"的 div,但我无法获取该 ID,因此无法显示地图.我尝试过 HTML 绑定、属性绑定,但它不起作用.我是淘汰赛的新手.请提出一些方法
你应该像这样使用自定义绑定:
ko.bindingHandlers.map = {初始化:函数(元素,valueAccessor,allBindingsAccessor,viewModel){var mapObj = ko.utils.unwrapObservable(valueAccessor());var latLng = 新的 google.maps.LatLng(ko.utils.unwrapObservable(mapObj.lat),ko.utils.unwrapObservable(mapObj.lng));var mapOptions = { 中心:latLng,变焦:5,mapTypeId: google.maps.MapTypeId.ROADMAP};mapObj.googleMap = new google.maps.Map(element, mapOptions);}};
您的 HTML 将如下所示:
最后你的视图模型:
function MyViewModel() {var self = this;self.myMap = ko.observable({纬度:ko.observable(55),lng: ko.observable(11)});}
这是一个fiddle,它的作用比你的要多一些正在询问,但也适用于您的情况.
I am making a single page app where in the second view I need to display the Google map. I am using the Google maps API where the map object is to be created.
var map = new google.maps.Map(mapId, {
zoom: 5,
center: new google.maps.LatLng(55, 11),
mapTypeId: google.maps.MapTypeId.ROADMAP
});
The parameter mapId
is giving me a problem. The view contains a div with id say "mapId", but I am not able to get the id and so the map cannot be displayed. I tried HTML binding, attribute binding but it does not work. I am new to knockout. Please suggest some method
解决方案 You should use a custom binding like so:
ko.bindingHandlers.map = {
init: function (element, valueAccessor, allBindingsAccessor, viewModel) {
var mapObj = ko.utils.unwrapObservable(valueAccessor());
var latLng = new google.maps.LatLng(
ko.utils.unwrapObservable(mapObj.lat),
ko.utils.unwrapObservable(mapObj.lng));
var mapOptions = { center: latLng,
zoom: 5,
mapTypeId: google.maps.MapTypeId.ROADMAP};
mapObj.googleMap = new google.maps.Map(element, mapOptions);
}
};
Your HTML would look like this:
<div id="mapDiv" data-bind="style:{width:'300px',height:'300px'},map:myMap"></div>
Finally your view model:
function MyViewModel() {
var self = this;
self.myMap = ko.observable({
lat: ko.observable(55),
lng: ko.observable(11)});
}
Here is a fiddle that does a bit more than what you are asking but should work fine for your case as well.
这篇关于谷歌地图和淘汰赛的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文