简体   繁体   中英

Google Maps API v3 labels and markers in loop

I can create markers in a loop but I am not able to add labels in the same loop. Is there a way to do this? Can somebody share the code to do that? Label has to be SYD, MEL, PERTH as in the array.

 var cities = {
'SYD'               :       [-21.459866     ,   119.498334      ],
'MEL'               :       [-26.233502     ,   119.323756      ],
'PERTH'             :       [-31.283012     ,   119.444157      ]
}


for (var key in cities) {
    var data = cities[key];
    var marker = new google.maps.Marker({
        position: new google.maps.LatLng (data[0], data[1]),
        map: map,
        icon: image,
        title: 'test',
    });

Not sure about this section

 var label = new Label({
       map: map
     });


     label.bindTo('position', marker, 'position');
     label.bindTo('text', marker, 'position');
var cities = {
'SYD'               :       [-21.459866     ,   119.498334      ],
'MEL'               :       [-26.233502     ,   119.323756      ],
'PERTH'             :       [-31.283012     ,   119.444157      ]
}


function initialize() {
    var bangalore = { lat: -21.459866, lng:  119.498334 };
    var map = new google.maps.Map(document.getElementById('map'), {
        zoom: 12,
        center: bangalore
    });

    // This event listener calls addMarker() when the map is clicked.
    google.maps.event.addListener(map, 'click', function(event) {
        addMarker(event.latLng, map);
    });
    var cities = {
        'SYD'               :       [-21.459866     ,   119.498334      ],
        'MEL'               :       [-21.456866     ,   119.518334      ],
        'PERTH'             :       [-21.457866     ,   119.528334      ]
    };
    for (var key in cities) {
        var data = cities[key];
        var t={ lat: data[0], lng:  data[1] };
        var marker = new google.maps.Marker({
            position: t,
            label: key,
            map: map
        });
    }
    // Add a marker at the center of the map.
}

You forgot add label parameter while create marker. See this fiddle for ref https://jsfiddle.net/6ou0n2fk/

try this code

function addMarker(myLatLng) {
      var marker = new google.maps.Marker({
        position: myLatLng,
        icon: icons['info'].icon,
        map: map
      });
    }
for(i=0; i<data.length; i++){
             var myLatLng = {lat: parseFloat(data[i].lat), lng: parseFloat(data[i].lng)};

      addMarker(myLatLng);

             // features.push([position: new google.maps.LatLng(23.0264288,72.5207211),type: 'info'];
        }

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM