javascript - 如何在 Google Maps API 中 move 标记

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

我正在使用 Google Maps API V3,我正在尝试让标记在屏幕上 move 。这是我拥有的:

<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no" />
<style type="text/css">
  html { height: 100% }
  body { height: 100%; margin: 0; padding: 0 }
  #map_canvas { height: 100% }
</style>
<script type="text/javascript"
    src="http://maps.googleapis.com/maps/api/js?sensor=false">
</script>
<script type="text/javascript">
function initialize() {
  var myLatLng = new google.maps.LatLng(50,50);
  var myOptions = {
    zoom: 4,
    center: myLatLng,
    mapTypeId: google.maps.MapTypeId.ROADMAP
  }
  var map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);

  image = 'bus.gif';
  marker = new google.maps.Marker({position: myLatLng, map: map, icon: image});

  marker.setMap(map);
}

function moveBus()
{
  // Move Bus
}

</script>
</head>

<body onload="initialize()">
<script type="text/javascript">
moveBus();
</script>
<div id="map_canvas" style="height: 500px; width: 500px;"></div>

</body>
</html>

现在我尝试将//Move Bus 替换为

marker.setPosition(new google.maps.LatLng(0,0));

但这并没有做任何事情。那是我在 API 引用中看到的命令。我对 Javascript 也比较陌生,所以这可能是我的 JS 错误。

最佳答案

moveBus()initialize() 之前被调用。尝试将该行放在 initialize() 函数的末尾。 Lat/Lon 0,0 也在 map 之外(它是坐标,而不是像素),所以当它 move 时你看不到它。尝试 54,54。如果您希望 map 的中心 move 到新位置,请使用 panTo()

演示:http://jsfiddle.net/ThinkingStiff/Rsp22/

HTML:

<script src="http://maps.googleapis.com/maps/api/js?sensor=false"></script>
<div id="map-canvas"></div>

CSS:

#map-canvas 
{ 
height: 400px; 
width: 500px;
}

脚本:

function initialize() {

    var myLatLng = new google.maps.LatLng( 50, 50 ),
        myOptions = {
            zoom: 4,
            center: myLatLng,
            mapTypeId: google.maps.MapTypeId.ROADMAP
            },
        map = new google.maps.Map( document.getElementById( 'map-canvas' ), myOptions ),
        marker = new google.maps.Marker( {position: myLatLng, map: map} );

    marker.setMap( map );
    moveBus( map, marker );

}

function moveBus( map, marker ) {

    marker.setPosition( new google.maps.LatLng( 0, 0 ) );
    map.panTo( new google.maps.LatLng( 0, 0 ) );

};

initialize();

关于javascript - 如何在 Google Maps API 中 move 标记,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8024784/

相关文章:

java - Android 刷新图库强制关闭应用程序

python - PySide Qt4 - Qtabwidget - 禁用单个 q 选项卡小部件的拖放

JavaScript 等于 "0"返回 true

google-maps - 错误: Google Maps API error: MissingKeyMapError

javascript - 使用 jQuery.countdownTimer.js 获取剩余时间值

google-maps-api-3 - 带有 Google 卫星图层的 Leaflet Map API

javascript - Google Maps API v3 - 基于 IP 的地理位置

c++ - 无法 move std::any

javascript从客户端保存/加载图像+文本数据

javascript - 使用 Jquery/Js 以 "2015-06-23"格式获取 7 天前的日期