2016-06-26 8 views
-3

Ich versuche, 3 Markierungen auf Google Map zu platzieren.For Schleife durch Array zeigt nur letzten Wert, Google Map

In JavaScript schrieb ich meine Schleife wie unten

var places = ["Bondi Beach", "Coogee Beach", "Cronulla Beach"]; 
var lat = [-33.890542, -33.923036, -34.028249]; 
var lng = [151.274856, 151.259052, 151.157507]; 

var z=0; 

for (tot=lat.length; z < tot; z++) { 
    var locations = [ 
     [places[z], lat[z], lng[z]] 
    ]; 
} 

Dann initialisiert ich meine Karte

var map; 
var markers = []; 

function init(){ 
    map = new google.maps.Map(document.getElementById('map_canvas'), { 
    zoom: 10, 
    center: new google.maps.LatLng(-33.92, 151.25), 
    mapTypeId: google.maps.MapTypeId.ROADMAP 
    }); 

    var num_markers = locations.length; 
    for (var i = 0; i < num_markers; i++) { 
    markers[i] = new google.maps.Marker({ 
     position: {lat:locations[i][1], lng:locations[i][2]}, 
     map: map, 
     html: locations[i][0], 
     id: i, 
    }); 

    google.maps.event.addListener(markers[i], 'click', function(){ 
     var infowindow = new google.maps.InfoWindow({ 
     id: this.id, 
     content:this.html, 
     position:this.getPosition() 
     }); 
     google.maps.event.addListenerOnce(infowindow, 'closeclick', function(){ 
     markers[this.id].setVisible(true); 
     }); 
     this.setVisible(false); 
     infowindow.open(map); 
    }); 
    } 
} 

init(); 

dieser Ausgang eine Markierung jedoch nur (die letzte), ich frage mich, was ist falsch mit meiner Schleife?

Antwort

2
for (tot=lat.length; z < tot; z++) { 
    var locations = [ 
     [places[z], lat[z], lng[z]] 
    ]; 
} 

Hier überschreiben Sie das Array locations bei jeder Iteration. Schieben Sie stattdessen die neuen Elemente in das Array.

var locations = [] 
for (tot=lat.length; z < tot; z++) { 
    locations.push([places[z], lat[z], lng[z]]); 
} 
+1

Ich glaube, var inside loop ist ein Tippfehler. :) –

+0

Mit der letzten Bearbeitung funktioniert es jetzt! Danke euch allen, ich fange gerade an, JS zu lernen – NineCattoRules