I am trying to implement markers on my static webpage using Javascript, KnockoutJS and google maps API. The page loads up the initMaps() function but when I try to load the markers they are not showing up. Please help me, I am using MVVM for the first time and let me know where I am wrong.
map.html goes here :
<!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());
}
The markers must be attached to the map, which is missing in your code.
This can be done when instantiating a Marker
via the property map
.
this.marker = new google.maps.Marker({
title: this.title,
position: this.location,
animation: google.maps.Animation.DROP,
map: map
});
or later via the method setMap
.
this.marker.setMap(map);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.