使用Knockout.js初始化Google Map(ES6语法)

时间:2019-01-06 16:27:31

标签: javascript knockout.js

HTML:在start = datetime.date(2017, 12, 29) end = datetime.date(2018, 12, 29) import pandas_datareader.data as web f = web.DataReader('GOOGL', 'iex', start, end) f = f.head() fig, ax1 = plt.subplots() ax1.bar(x = f.index, height = f.volume/1000, width = 0.3) ax1.set_ylabel('volumn in 1000s', color='b') ax1.tick_params('y', colors='b') ax2 = ax1.twinx() ax2.plot(f.index, f.open, 'g') ax2.set_ylabel('open price', color='g') ax2.tick_params('y', colors='g') fig.tight_layout() plt.show() 行中,我不知道如何data-bind

<div id="map"></div>

JavaScript:一切似乎还好吧?

<div>            
<input data-bind="value: cityInput" type="text" class="search-input" id="city" placeholder="Enter a city"/>
<input data-bind="value: neighborhoodInput" type="text" class="search-input" id="neighborhood" placeholder="Enter a location in this city" value="Brooklyn"/>
<div data-bind="initMap()" id="map"></div>
</div>
<script async defer src="https://maps.googleapis.com/maps/api/js?libraries=geometry,places&v=weekly&key=APIKEY&callback=initMap"></script>
<script type="text/javascript" src="js/knockout-3.4.2.js"></script>

以某种方式,地图未按预期显示。它不是仅由于HTML中缺少 class ViewModel { constructor() { this.cityInput = ko.observable("New York"); this.neighborhoodInput = ko.observable("Brooklyn"); this.placeInput = ko.observable("Restaurants"); } initMap() { let geocoder = new google.maps.Geocoder(); geocoder.geocode({address: this.cityInput()}, function(results, status) { if (status == google.maps.GeocoderStatus.OK) { let cityLat = results[0].geometry.location.lat().valueOf(); let cityLng = results[0].geometry.location.lng().valueOf(); let map = new google.maps.Map(document.getElementById("map"), { center: {lat: cityLat, lng: cityLng}, zoom: 10, mapTypeControl: false }); let cityOptions = {types: ["(cities)"]}; let cityAutocomplete = new google.maps.places.Autocomplete(document.getElementById("city"), cityOptions); cityAutocomplete.bindTo("bounds", map); let searchBox = new google.maps.places.SearchBox(document.getElementById("place")); searchBox.setBounds(map.getBounds()); } }); } } ko.applyBindings(new ViewModel()); 而显示,还是Javascript中有任何错误?

1 个答案:

答案 0 :(得分:0)

鉴于Map API的工作方式,我认为您无法使用Knockout的数据绑定对其进行初始化(如果我错了,任何人都可以纠正我)。

试试看-只需在viewModel的末尾调用initMap函数,然后从HTML中删除数据绑定。

<div id="map"></div>

-

class ViewModel {
    constructor() {
        ...
    }
    initMap() {
        ...
    }
    initMap()
}