Aessandro
Aessandro

Reputation: 5761

Google map drag pin from inside a div on google map

I have the following 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>

The image is a custom pin which I would like to drag on the map and get the coordinates related to it. I have my map set up. I can't figure out (if possible) how to drag a static image from inside a html mark up and drop it on the map to make it function like a pin.

I am ok with adding a mraker:

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

I am trying to copy this example (http://www.wolfpil.de/v3/drag-from-outside.html) but I am getting the following error:

'Cannot read property 'offsetWidth' of null '

This is my index page: http://jsfiddle.net/ud3p7m96/

Upvotes: 1

Views: 1362

Answers (2)

Emmanuel Delay
Emmanuel Delay

Reputation: 3679

(After hearing what Alex plans with those markers, I extend the code. Now it makes a polygon of those markers)

<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>

Upvotes: 0

Emmanuel Delay
Emmanuel Delay

Reputation: 3679

You can copy/paste this code, it works as is. What I did:

  • I use jQuery-UI Draggable. When the client starts dragging, I set a variable to remember where over the pin the mouse is. With this value you can calculate the distance from the mouse position to the active point on the pin (= bottom center)

  • When dropping the pin, I use overlay.getProjection().fromContainerPixelToLatLng to ask Google for the coordinates corresponding to a position (in pixels) on the map

There is more comment in the code

<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>

Upvotes: 1

Related Questions