如何在Google Maps API中移动标记

gsi*_*011 41 javascript move google-maps-api-3 google-maps-markers

我正在使用谷歌地图API V3,我正试图在屏幕上移动标记.这就是我所拥有的:

<!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>
Run Code Online (Sandbox Code Playgroud)

现在我尝试用@替换//移动总线

marker.setPosition(new google.maps.LatLng(0,0));
Run Code Online (Sandbox Code Playgroud)

但那没有做任何事情.这是我在API参考上看到的命令.我对Javascript也比较陌生,所以这可能是我的JS错误.

Thi*_*iff 55

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

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

HTML:

<script src="http://maps.googleapis.com/maps/api/js?sensor=false"></script>
<div id="map-canvas"></div>
Run Code Online (Sandbox Code Playgroud)

CSS:

#map-canvas 
{ 
height: 400px; 
width: 500px;
}
Run Code Online (Sandbox Code Playgroud)

脚本:

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();
Run Code Online (Sandbox Code Playgroud)


小智 10

只需尝试创建标记并将draggable属性设置为true.代码如下:

Marker = new google.maps.Marker({
    position: latlon,
    map: map,            
    draggable: true,
    title: "Drag me!"
});
Run Code Online (Sandbox Code Playgroud)

我希望这有帮助!