我正在尝试使用Javascript、KnockoutJS和google地图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());
}
标记必须附加到映射,而映射在代码中丢失。
这可以在通过属性map
实例化Marker
时完成。
this.marker = new google.maps.Marker({
title: this.title,
position: this.location,
animation: google.maps.Animation.DROP,
map: map
});
或者稍后通过方法CCD_ 3。
this.marker.setMap(map);