【问题标题】:Google map drag pin from inside a div on google map谷歌地图从谷歌地图上的一个div内部拖动图钉
【发布时间】:2014-10-16 10:24:34
【问题描述】:

我有以下 HTML:

<div id="map-canvas"></div>
<div class="controls">
    <p>Zoom</p>
    <i class="icon-plus-sign"></i> 
    <i class="icon-minus-sign"></i>

    <div class="pinWrapper">
        <p>Drop your pin</p>
        <img src="https://cdn0.iconfinder.com/data/icons/20-flat-icons/128/location-pointer.png">
    </div>
</div>

图像是一个自定义图钉,我想将其拖到地图上并获取与其相关的坐标。我的地图已经设置好了。我不知道(如果可能的话)如何从 html 标记中拖动静态图像并将其拖放到地图上以使其像图钉一样发挥作用。

我可以添加一个 mraker:

var marker = new google.maps.Marker({
    position: myLatlng,
    map: map,
    title:"title here"
});

我正在尝试复制此示例 (http://www.wolfpil.de/v3/drag-from-outside.html),但出现以下错误:

'无法读取属性'offsetWidth' of null'

这是我的索引页:http://jsfiddle.net/ud3p7m96/

【问题讨论】:

    标签: javascript google-maps


    【解决方案1】:

    您可以复制/粘贴此代码,它按原样工作。 我做了什么:

    • 我使用 jQuery-UI Draggable。当客户端开始拖动时,我设置了一个变量来记住鼠标在图钉上方的位置。使用此值,您可以计算从鼠标位置到引脚上的活动点(= 底部中心)的距离

    • 删除图钉时,我使用 overlay.getProjection().fromContainerPixelToLatLng 向 Google 询问地图上某个位置(以像素为单位)对应的坐标

    代码中有更多注释

    <div id="map-canvas"></div>
    <div class="controls">
        <p>Zoom</p>
        <i class="icon-plus-sign"></i> 
        <i class="icon-minus-sign"></i>
    
        <div class="pinWrapper">
            <p>Drop your pin</p>
            <img src="https://cdn0.iconfinder.com/data/icons/20-flat-icons/128/location-pointer.png">
        </div>
    </div>
    
    <link rel="stylesheet" href="//ajax.googleapis.com/ajax/libs/jqueryui/1.11.1/themes/smoothness/jquery-ui.css" />
    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
    <script src="//ajax.googleapis.com/ajax/libs/jqueryui/1.11.1/jquery-ui.min.js"></script>
    <script src="http://maps.googleapis.com/maps/api/js?libraries=geometry,visualization,drawing,places&sensor=false"></script>
    <script>
    $(document).ready(function() {
      var mouseStartDrag=[0,0];
      var newMarker;
      var activePointPin = [47,128];  // = bottom center of the pin.  Change this value if the pin is changed
    
      // jQuery-UI draggable
      $('.pinWrapper img').draggable({
        start: function(event) {
          // this gives you the position of the mouse relative to the image.
          mouseStartDrag = [event.offsetX, event.offsetY];    
        },
        stop: function(event) {
          // we look at the mouse position, subtract it from the position of the map, so we get the mouse position over the map
          var coordinatesOverDiv = [event.clientX - $('#map-canvas').position().left, event.clientY - $('#map-canvas').position().top];
          // we don't want the mouse position, we want the position of the active point on the pin.
          coordinatesOverDiv = [
            coordinatesOverDiv[0] + activePointPin[0] - mouseStartDrag[0], 
            coordinatesOverDiv[1] + activePointPin[1] - mouseStartDrag[1]
          ];
          // ask Google to get the position, corresponding to a pixel on the map
          var pixelLatLng = overlay.getProjection().fromContainerPixelToLatLng( new google.maps.Point(coordinatesOverDiv[0], coordinatesOverDiv[1]) );
          // set a new marker
          newMarker = new google.maps.Marker({
            map: map,
            position: pixelLatLng
          });
          // set the pin back to its original position, @see http://stackoverflow.com/questions/15193640/jquery-ui-draggable-reset-to-original-pos
          $(this).animate({
              top: "0px",
              left: "0px"
          });
    
        }
      });
      initialize();
    });
    var map;
    var overlay;
    
    // Google Maps
    function initialize() {
      var mapOptions = {
        zoom: 8,
        center: new google.maps.LatLng(50.5, 4.5),  // Over Belgium
        mapTypeId: google.maps.MapTypeId.TERRAIN
      };
      map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
      // this overlay will be used to calculate mouse coordinates to Lat/Lng
      overlay = new google.maps.OverlayView();
      overlay.draw = function() {};
      overlay.setMap(map);
    }
    </script>
    <style>
    #map-canvas {
      height:400px;
    }
    </style>
    

    【讨论】:

    • 很高兴为您提供帮助。这是一个很好的问题;总有一天我可能会需要这个
    • 我如何能够检索有关放置在地图上的每个标记的信息。例如:职位。
    • 根据您的脚本,这是否足以获取每个标记位置? newMarker.getPosition()
    • 在我设置新标记的地方,您应该将 newMarker 推送到标记数组;然后你可以访问他们的属性。你打算用这些标记做什么?当客户点击标记时检索信息?创建标记时保留位置列表?使用 AJAX 上传这些标记? ...请解释一下。
    • 这个想法是在地图上放置一些图钉,这将创建一个多边形。根据每个引脚位置,我将生成有关该区域的天气信息。
    【解决方案2】:

    (在听到 Alex 对这些标记的计划后,我扩展了代码。 现在它制作了这些标记的多边形)

    <div id="map-canvas"></div>
    <div class="controls">
        <p>Zoom</p>
        <i class="icon-plus-sign"></i> 
        <i class="icon-minus-sign"></i>
    
        <div class="pinWrapper">
            <p>Drop your pin</p>
            <img src="https://cdn0.iconfinder.com/data/icons/20-flat-icons/128/location-pointer.png">
        </div>
    </div>
    <hr>
    <input type="button" id="make_polygon" value="Make Polygon">
    <div id="points"></div>
    
    <link rel="stylesheet" href="//ajax.googleapis.com/ajax/libs/jqueryui/1.11.1/themes/smoothness/jquery-ui.css" />
    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
    <script src="//ajax.googleapis.com/ajax/libs/jqueryui/1.11.1/jquery-ui.min.js"></script>
    <script src="http://maps.googleapis.com/maps/api/js?libraries=geometry,visualization,drawing,places&sensor=false"></script>
    <script>
    $(document).ready(function() {
      var mouseStartDrag=[0,0];
      var newMarker;
      var activePointPin = [47,128];  // = bottom center of the pin.  Change this value if the pin is changed
    
      // jQuery-UI draggable
      $('.pinWrapper img').draggable({
        start: function(event) {
          // this gives you the position of the mouse relative to the image.
          mouseStartDrag = [event.offsetX, event.offsetY];    
        },
        stop: function(event) {
          // we look at the mouse position, subtract it from the position of the map, so we get the mouse position over the map
          var coordinatesOverDiv = [event.clientX - $('#map-canvas').position().left, event.clientY - $('#map-canvas').position().top];
          // we don't want the mouse position, we want the position of the active point on the pin.
          coordinatesOverDiv = [
            coordinatesOverDiv[0] + activePointPin[0] - mouseStartDrag[0], 
            coordinatesOverDiv[1] + activePointPin[1] - mouseStartDrag[1]
          ];
          // ask Google to get the position, corresponding to a pixel on the map
          var pixelLatLng = overlay.getProjection().fromContainerPixelToLatLng( new google.maps.Point(coordinatesOverDiv[0], coordinatesOverDiv[1]) );
          // set a new marker
          newMarker = new google.maps.Marker({
            map: map,
            position: pixelLatLng
          });
          // push the new marker in an array
          markers.push(newMarker);
    
          // display the coordinates.  Feel free to remove this, it's just display
          $('#points').append('<div>' + newMarker.position.lat() +','+ newMarker.position.lng() + '</div>');
    
          // set the pin back to its original position, @see http://stackoverflow.com/questions/15193640/jquery-ui-draggable-reset-to-original-pos
          $(this).animate({
              top: "0px",
              left: "0px"
          });
    
        }
      });
      // polygon
      $('#make_polygon').click(function() {
        var polygonPoints = [];
        for (var i=0; i<markers.length; i++) {    
          polygonPoints.push(new google.maps.LatLng( markers[i].position.lat(), markers[i].position.lng() ));
        }
        // Construct the polygon.
        myPolygon = new google.maps.Polygon({
          paths: polygonPoints,
          strokeColor: '#FF0000',
          strokeOpacity: 0.8,
          strokeWeight: 2,
          fillColor: '#FF0000',
          fillOpacity: 0.35
        });
        // put the polygon on the map
        myPolygon.setMap(map);
      });
    
      initialize();
    });
    var map;
    var overlay;
    var markers = [];
    
    // Google Maps
    function initialize() {
      var mapOptions = {
        zoom: 8,
        center: new google.maps.LatLng(50.5, 4.5),  // Over Belgium
        mapTypeId: google.maps.MapTypeId.TERRAIN
      };
      map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
      // this overlay will be used to calculate mouse coordinates to Lat/Lng
      overlay = new google.maps.OverlayView();
      overlay.draw = function() {};
      overlay.setMap(map);
    }
    </script>
    <style>
    #map-canvas {
      height:400px;
    }
    </style>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-07-27
      • 1970-01-01
      • 2017-11-18
      • 1970-01-01
      • 1970-01-01
      • 2011-09-17
      • 1970-01-01
      相关资源
      最近更新 更多