谷歌地图和knockoutjs [英] Google maps and knockoutjs

查看:88
本文介绍了谷歌地图和knockoutjs的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在制作单页应用,在第二个视图中,我需要显示Google地图。我正在使用要创建地图对象的Google地图API。

  var map = new google.maps.Map(mapId,{
zoom:5,
center :new google.maps.LatLng(55,11),
mapTypeId:google.maps.MapTypeId.ROADMAP
});

参数 mapId 给我一个问题。该视图包含一个ID为mapId的div,但我无法获取该ID,因此地图无法显示。我尝试了HTML绑定,属性绑定,但它不起作用。我是新来的淘汰赛。请提供一些方法

解决方案

您应该使用像这样的自定义绑定:



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);
}
};

您的HTML看起来像这样:

 < div id =mapDivdata-bind =style:{width:'300px',height:'300px'},map:myMap >< / DIV> 

最后您的视图模型:

  function MyViewModel(){
var self = this;
self.myMap = ko.observable({
lat:ko.observable(55),
lng:ko.observable(11)});
}

这是 $ b $


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.

这篇关于谷歌地图和knockoutjs的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆