【问题标题】:I want to randomly change Google Marker position through loop or something我想通过循环或其他方式随机更改 Google Marker 位置
【发布时间】:2020-03-08 21:06:25
【问题描述】:

我是 Google API 的新手,我想在 google 地图上自动更改 Google Marker 的位置,五秒钟后它会在地图上自动更改位置。我没有纬度和经度的数据库。 我的意思是说标记在地图上随机改变它的位置。

【问题讨论】:

  • 到目前为止你尝试了什么?
  • 我的意思是说标记在大约 5 秒后随机改变它在地图上的位置

标签: javascript laravel google-maps-markers


【解决方案1】:

免责声明:您可以使用 vanilla Javascript 实现此目的。

由于您没有数据库,您可以使用LatLng class 的数组来指定要显示的坐标:

  //an array of geographical coordinates
  var locations = [
      new google.maps.LatLng(6.528166, 20.439864), //somewhere in Africa
      new google.maps.LatLng(34.494890, 103.854720), //somewhere in China
      new google.maps.LatLng(51.802090, 7.771800), // somewhere in Germany
      new google.maps.LatLng(46.153450, -101.948783), // somewhere in US
      new google.maps.LatLng(-11.495951, -49.266451), // somewhere in Brazil
      new google.maps.LatLng(-80.287421, 23.599101) // somewhere in Antartica
  ];

之后,您可以使用setInterval() 函数,该函数将包含随机化地理坐标数组中的项目并更改地图和标记位置的代码。

// set interval that will repeat every after 5 seconds
setInterval(function() {

    // pick random coordinates from the locations array
    var randomLocation = locations[Math.floor(Math.random() * locations.length)];

    // change the map center
    map.setCenter(randomLocation);

    // change the marker position
    marker.setPosition(randomLocation);
}, 5000);

请找到工作示例here

我希望这会有所帮助!

【讨论】:

    猜你喜欢
    • 2023-03-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多