簡體   English   中英

循環中的 Google Maps API v3 標簽和標記

[英]Google Maps API v3 labels and markers in loop

我可以在循環中創建標記,但我無法在同一個循環中添加標簽。 有沒有辦法做到這一點? 有人可以分享代碼來做到這一點嗎? 標簽必須是數組中的 SYD、MEL、PERTH。

 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',
    });

不確定這部分

 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.
}

您在創建標記時忘記添加標簽參數。 請參閱此小提琴以獲取參考https://jsfiddle.net/6ou0n2fk/

試試這個代碼

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'];
        }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM