在谷歌地图中用鼠标移动标记

时间:2013-12-10 07:28:46

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

我想在谷歌地图上用鼠标移动事件移动标记。

以下是我在谷歌地图上添加标记的代码。

<!DOCTYPE html>
<html>
<head>
 <meta name="viewport" content="initial-scale=1.0, user-scalable=no">
<meta charset="utf-8">
<title>Simple markers</title>
<style>
  html, body, #map-canvas {
    height: 100%;
    margin: 0px;
    padding: 0px
  }
</style>
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false"></script>
<script>
function initialize() {
 var myLatlng = new google.maps.LatLng(-25.363882,131.044922);
 var mapOptions = {
   zoom: 4,
  center: myLatlng
 }
 var map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);

 var marker = new google.maps.Marker({
  position: myLatlng,
  map: map,
  title: 'Hello World!'
 });
 }

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

</script>
</head>
<body>
<div id="map-canvas"></div>
</body>

这是一个取自https://developers.google.com/maps/documentation/javascript/examples/marker-simple

的简单标记示例

在鼠标移动时,我想用鼠标移动标记。但我不知道该怎么做

3 个答案:

答案 0 :(得分:2)

 var marker = new google.maps.Marker({
                position: map.getCenter(),
                map: map,
                title: 'Click to zoom'
            });

            google.maps.event.addListener(map, 'mousemove', function(e) {
                marker.setPosition(e.latLng);
            });

使用此代码,我们可以在谷歌地图上用鼠标移动标记

答案 1 :(得分:2)

如果我明白你想要用鼠标移动标记。不一定要在mousemouve事件中移动它。为了能够做到这一点,您只需将标记的draggable属性设置为true

考虑以下例子:

<!DOCTYPE html>
<html>
<head>
 <meta name="viewport" content="initial-scale=1.0, user-scalable=no">
<meta charset="utf-8">
<title>Simple markers</title>
<style>
  html, body, #map-canvas {
    height: 100%;
    margin: 0px;
    padding: 0px
  }
</style>
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false"></script>
<script>
function initialize() {
 var myLatlng = new google.maps.LatLng(-25.363882,131.044922);
 var mapOptions = {
   zoom: 4,
  center: myLatlng
 }
 var map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);

 var marker = new google.maps.Marker({
  position: myLatlng,
  map: map,
  title: 'Hello World!',
  draggable: true
 });
 }

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

</script>
</head>
<body>
<div id="map-canvas"></div>
</body>

要引用标记已阅读的所有属性:MarkerOptions

答案 2 :(得分:0)

请参阅谷歌地图中的事件监听器this