我正在尝试使用Javascript,KnockoutJS和Google Maps API在我的静态网页上实现标记。该页面加载了initMaps()函数,但是当我尝试加载标记时,它们没有显示出来。请帮助我,我是第一次使用MVVM,请告诉我哪里错了。
map.html转到此处:
<!DOCTYPE html>
<html>
<head>
<style>
html,
body {
font-family: Arial, sans-serif;
height: 100%;
margin: 0;
padding: 0;
}
#map {
height: 100%;
}
</style>
</head>
<body>
<div id="map"></div>
<script src="/Users/jainamshah/Desktop/Nhmap/app.js"></script>
<script type='text/javascript' src='knockout.js'></script>
<script async defer
src="https://maps.googleapis.com/maps/api/js?key=#KEPTPRIVATE&callback=initMap">
</script>
</body>
</html>
app.js:
var locations = [
{title: 'by CHLOE',
location: {lat: 42.351114, lng: -71.045021}
},
{title: 'Tamazcal',
location: {lat: 42.348904, lng: -71.038292}
},
{title: 'Boston Kashmir',
location: {lat: 42.349317, lng: -71.083926}
},
{title: 'Max Brenner',
location: {lat: 42.349348, lng: -71.080829}
},
{title: 'Thai Basil',
location: {lat: 42.350925, lng: -71.076643}
},
{title: 'Boston Burger CO`',
location: {lat: 42.34681, lng: -71.088473}
}
];
var map;
var markers = [];
function initMap() {
// Constructor creates a new map - only center and zoom are required.
map = new google.maps.Map(document.getElementById('map'), {
center: {lat: 42.360083, lng: -71.05888},
zoom: 13
});
bindItAll();
}
var Model = function(data){
this.title = data.title;
this.location = data.location;
this.marker = new google.maps.Marker({
title: this.title,
position: this.location,
animation: google.maps.Animation.DROP,
});
var largeInfowindow = new google.maps.InfoWindow();
this.marker.addListener('click', function() {
populateInfoWindow(this, largeInfowindow);
});
function populateInfoWindow(marker, infowindow) {
if (infowindow.marker != marker) {
infowindow.marker = marker;
infowindow.setContent('<div>' + marker.title + '</div>');
infowindow.open(map, marker);
// Make sure the marker property is cleared if the infowindow is closed.
infowindow.addListener('closeclick',function(){
infowindow.setMarker = null;
});
}
}
}
var ViewModel = function(){
var self = this;
this.Locations = ko.observableArray();
locations.forEach(function(data){
self.Locations.push( new Model(data) );
});
}
function bindItAll() {
ko.applyBindings(new ViewModel());
}
答案 0 :(得分:1)
标记必须附加到地图上,这是您的代码中所缺少的。
这可以通过属性Marker
实例化map
来完成。
this.marker = new google.maps.Marker({
title: this.title,
position: this.location,
animation: google.maps.Animation.DROP,
map: map
});
或稍后通过方法setMap
。
this.marker.setMap(map);