0

我正在尝试创建一个地图,我可以在其中循环遍历一系列不同的位置。然后我想设置一个随机坐标的位置。所以我希望每次重新加载页面时都有一个坐标为我随机放置一个标记!

    function initialize() {
    //here is the starting for the map, where it will begin to show
    var latlng = new google.maps.LatLng(59.2982762, 17.9970823);

    var myOptions = {
      zoom: 13,
      center: latlng,
      mapTypeId: google.maps.MapTypeId.ROADMAP
    };
      //below are the markers coordinates, change it to your coordinates
        var map = new google.maps.Map(document.getElementById('map-canvas'),  myOptions);

        var i = 0;
        function randAreas() {
        var flagAreas = (Math.round(Math.random())-0.5);
    }

      var flagAreas = [

      [59.2967322, 18.0009393],
      [59.2980245, 17.9971503],
      [59.2981078, 17.9980875],
      [59.2982762, 17.9970823],
      [59.2987638, 17.9917639],
      [59.2987649, 17.9917824],
      [59.2987847, 17.9917731],
      [59.2988498, 17.991684],
      [59.2988503, 17.9981593],
      [59.3008233, 18.0041763],
      [59.3014033, 18.0068793],
      [59.3016619, 18.0137766]
      ];

    return flagAreas;

    flagAreas.sort(randAreas);

      //script counts the array of coordinates
      //for (var i = 0; i < flagAreas.length; i++) {
        var marker = new google.maps.Marker({
          position: new google.maps.LatLng(flagAreas[i], flagAreas[i]),
          map: map,
        });
      }

 window.onload = initialize;

</script>
4

2 回答 2

0

首先,将 map 变量移到初始化之外,以防您需要在代码的其他地方使用它。

var map;

function initialize() {

  var latlng = new google.maps.LatLng(59.2982762, 17.9970823);
  var myOptions = {
    zoom: 13,
    center: latlng,
    mapTypeId: google.maps.MapTypeId.ROADMAP
  };
  map = new google.maps.Map(document.getElementById('map-canvas'),  myOptions);

  var flagAreas = [
    [59.2967322, 18.0009393], [59.2980245, 17.9971503],
    [59.2981078, 17.9980875], [59.2982762, 17.9970823],
    [59.2987638, 17.9917639], [59.2987649, 17.9917824],
    [59.2987847, 17.9917731], [59.2988498, 17.991684],
    [59.2988503, 17.9981593], [59.3008233, 18.0041763],
    [59.3014033, 18.0068793], [59.3016619, 18.0137766]
  ];

洗牌 flagAreas 并获取第一个数组。

  var random = flagAreas.sort(function () { return Math.random() - 0.5 } )[0];

添加标记。

  var marker = new google.maps.Marker({
    position: new google.maps.LatLng(random[0], random[1]),
    map: map,
  });

}

window.onload = initialize;

小提琴

于 2013-10-21T09:38:28.877 回答
0

您的代码中有 3 个问题。

initialize1)未执行for循环的意外终止。

 return flagAreas;  //Remove this code

2)

flagAreas[i] //An array returns both lat and lng

position: new google.maps.LatLng(flagAreas[i], flagAreas[i]) //Wrong

替换喜欢

position: new google.maps.LatLng(flagAreas[i][0], flagAreas[i][1]) //Correct

,3)每当您到达最后一个选项时删除。

 map: map

最后在JSFiddle中检查这个

于 2013-10-21T09:28:32.333 回答