0👍
First of all let’s start with mocking the provided data for this purpose i will overwrite $.getJSON
var $ = {
getJSON : function(url, callback){
callback(
[{"foodtruck_name":"Emils Foodtruck","open_hours":"11:00-16:00","address":"Stigbergsliden 9","type_of_food":"Mexikanskt tema","webadress":"www.emilwallgren.se"},{"foodtruck_name":"Kodameras Truck","open_hours":"08:00-17:00","address":"F\u00f6rsta L\u00e5nggatan 16","type_of_food":"Cookies","webadress":"www.kodamera.se"}]
);
}
};
Then let’s create a small index.html to see results also include the used frameworks from their CDN urls
<!doctype html>
<html class="no-js" lang="">
<head>
<meta charset="utf-8">
<meta http-equiv="x-ua-compatible" content="ie=edge">
<title>Maps</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<style type="text/css">
#map{
width: 100%;
height: 300px;
}
</style>
</head>
<body>
<div id = "map"></div>
<script src="//cdn.jsdelivr.net/vue/1.0.25/vue.min.js"></script>
<script src="js/main.js"></script>
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCTlirlFFxIHhstDEeARWQTym5AeU4db1I&callback=initMap"></script>
</body>
</html>
It would have been awesome to have that provided in the question 🙂
The main issue with the initial code is, that the method geocoder.geocode is an asyncronous operation while the bindInfoWindow function was called within the status code OK condition, which is most likely executed far after the for loop already finished. That means all the arguments passed to the function is just data from the last iteration of the for loop.
To proof that asumption just put
geocoder.geocode({‘address’: address}, function(results, status) {
console.log(“outside”);
if (status === google.maps.GeocoderStatus.OK) {
console.log(“inside”);
}
});
into your code you will see outside being triggered twice before the inside is triggered. The inside is delayed because there are some requests to google to fullify before it is executed.
To make a quick fix just gather all the data in the first loop and add them utilizing a recursive function.
The full code looks like this (i wrapped the whole block into the default maps callback)
var $ = {
getJSON : function(url, callback){
callback(
[{"foodtruck_name":"Emils Foodtruck","open_hours":"11:00-16:00","address":"Stigbergsliden 9","type_of_food":"Mexikanskt tema","webadress":"www.emilwallgren.se"},{"foodtruck_name":"Kodameras Truck","open_hours":"08:00-17:00","address":"F\u00f6rsta L\u00e5nggatan 16","type_of_food":"Cookies","webadress":"www.kodamera.se"}]
);
}
};
initMap = function(){
var app = new Vue({
el: 'body',
data: {
users: $.getJSON("http://localhost:8000/data", function(data){
function bindInfoWindow(marker) {
marker.addListener('click', function() {
this.infowindow.setContent(this.infowindowContent)
this.infowindow.open(this.map, this);
});
}
var addmarkersRecursive = function addMarkers(markers){
if(markers.length > 0){
markerConfig = markers.shift();
geocoder.geocode({'address': markerConfig.address}, function(results, status) {
if (status === google.maps.GeocoderStatus.OK) {
var marker = new google.maps.Marker({
map: markerConfig.map,
position: results[0].geometry.location,
icon: markerConfig.image,
shape: markerConfig.shape,
infowindow : markerConfig.infowindow,
infowindowContent : markerConfig.contentString
});
bindInfoWindow(marker, markerConfig.map, markerConfig.infoWindow, markerConfig.contentString);
addmarkersRecursive(markers);
} else {
alert('Geocode was not successful for the following reason: ' + status);
}
});
}
};
var map = new google.maps.Map(document.querySelector('#map'), {
center: {lat: 57.708870, lng: 11.974560 },
zoom: 14
});
var geocoder = new google.maps.Geocoder();
var markers = [];
for (var i = 0; i < data.length; i++) {
var address = data[i]['address'] + ' Göteborg';
var contentString = '<h4 style="color: #ffc62d">' + data[i]['foodtruck_name'] + '</h4>'
+ '<b>Mat:</b> ' + data[i]['type_of_food']
+ '<br><b>Öppettider:</b> '+ data[i]['open_hours']
+ '<br><b>Adress:</b> '+ data[i]['address']
+ '<br><b>Hemsida:</b> '+ '<a href="http://' + data[i]['webadress'] + '" target="_blank">' + data[i]['webadress'] + '</a>';
var image = {
url: 'http://t1.gstatic.com/images?q=tbn:ANd9GcT_vg5Yh1dmbqL4cVfaBoZhFfPwXJIZhJ5MFU9Y6lm4173JsKb8XEFK',
// This marker is 20 pixels wide by 32 pixels high.
size: new google.maps.Size(45, 30),
// The origin for this image is (0, 0).
origin: new google.maps.Point(0, 0),
// The anchor for this image is the base of the flagpole at (0, 32).
anchor: new google.maps.Point(0, 30)
};
markers.push({
map : map,
address: address,
contentString: contentString,
image: image,
shape : {
coords: [1, 1, 1, 30, 45, 20, 18, 1],
type: 'poly'
},
infowindow : new google.maps.InfoWindow({maxWidth: 250 })
})
};
addmarkersRecursive(markers);
})
},
methods: {
createMap: function() {
var map = new google.maps.Map(document.querySelector('#map'), {
center: {lat: 57.708870, lng: 11.974560 },
zoom: 14
});
}
}
});
}