有没有办法将位置添加到使用javascript随机放置在谷歌地图中的标记的标签上?

时间:2017-06-01 13:47:27

标签: javascript google-maps google-maps-api-3 google-maps-markers

是否可以将LatLng添加到随机放置的标记的标签上以显示该标记的位置?还考虑了infoWindow选项,但还没有成功。

var map;
var markers = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
var markersIndex = 0;

function initialize() {
    var Wilm = new google.maps.LatLng(34.2257,-77.9447);
    var mapOptions = {
        zoom: 12,
        center: Wilm,
        mapTypeId: google.maps.MapTypeId.TERRAIN
    }
    map = new google.maps.Map(document.getElementById('map-
    canvas'),mapOptions);



    google.maps.event.addListener(map, 'click', function(event) {
            addMarker(event.latLng);
    });


}

function addMarker(location) {

        var marker = new google.maps.Marker({
        position: location,
        label: markers[markersIndex++ % markers.length],
        map: map
    });
    google.maps.event.addListener(marker, 'rightclick', function(event) {
            marker.setMap(null);
    });

    markers.push(marker);
}

google.maps.event.addDomListener(window, 'load', initialize);

1 个答案:

答案 0 :(得分:0)

不确定标签是什么意思。

这将使用带有latlng的信息窗口向地图添加标记:

    function initMap() {
  var Wilm = new google.maps.LatLng(34.2257, -77.9447);
  var mapOptions = {
    zoom: 12,
    center: Wilm,
    mapTypeId: google.maps.MapTypeId.TERRAIN
  }
  map = new google.maps.Map(document.getElementById('map'), mapOptions);

  google.maps.event.addListener(map, 'click', function(event) {
    placeMarker(event.latLng);
  });
}

function placeMarker(location) {


  var marker = new google.maps.Marker({
    position: location,
    map: map
  });

  var contentString = 'Lat' + marker.getPosition().lat() + ', lng:  ' + marker.getPosition().lng();

  var infowindow = new google.maps.InfoWindow({
    content: contentString
  });

  marker.addListener('click', function() {
    infowindow.open(map, marker);
  });
}



function initMap() {
  var Wilm = new google.maps.LatLng(34.2257, -77.9447);
  var mapOptions = {
    zoom: 12,
    center: Wilm,
    mapTypeId: google.maps.MapTypeId.TERRAIN
  }
  map = new google.maps.Map(document.getElementById('map'), mapOptions);

  google.maps.event.addListener(map, 'click', function(event) {
    placeMarker(event.latLng);
  });
}

function placeMarker(location) {


  var marker = new google.maps.Marker({
    position: location,
    map: map
  });

  var contentString = 'Lat' + marker.getPosition().lat() + ', lng:  ' + marker.getPosition().lng();

  var infowindow = new google.maps.InfoWindow({
    content: contentString
  });

  marker.addListener('click', function() {
    infowindow.open(map, marker);
  });
}

<div id="map"></div>
<!-- Replace the value of the key parameter with your own API key. -->
<script async defer src="https://maps.googleapis.com/maps/api/js?key=KEY&callback=initMap">


</script>
&#13;
&#13;
&#13;