luke luke - 7 months ago 107
Javascript Question

Keep marker/pin in the middle of the map while dragging

I want the marker/pin to scroll around and be in the center of the map while the user is dragging around the map. I have a simple jsfiddle (http://jsfiddle.net/upsidown/5xd1Lbpc/6/) where the pin will drop to the center of the map when the user stops dragging, but I want the pin to move with the dragging.

Google Maps JS

var center = new google.maps.LatLng(-33.013803, -71.551498);

var map = new google.maps.Map(document.getElementById('mapBox'), {
zoom: 18,
center: center,
mapTypeId: google.maps.MapTypeId.HYBRID
});

var myMarker = new google.maps.Marker({
position: center,
draggable: true,
map: map
});

google.maps.event.addListener(myMarker, 'dragend', function () {
map.setCenter(this.getPosition()); // Set map center to marker position
updatePosition(this.getPosition().lat(), this.getPosition().lng()); // update position display
});

google.maps.event.addListener(map, 'dragend', function () {
myMarker.setPosition(this.getCenter()); // set marker position to map center
updatePosition(this.getCenter().lat(), this.getCenter().lng()); // update position display
});

function updatePosition(lat, lng) {
document.getElementById('dragStatus').innerHTML = '<p> Current Lat: ' + lat.toFixed(4) + ' Current Lng: ' + lng.toFixed(4) + '</p>';
}


HTML

<div id='mapBox'></div>


Any ideas or thoughts on how to do this?

Answer

add this

google.maps.event.addListener(map, 'drag', function () {
  myMarker.setPosition(this.getCenter()); // set marker position to map center
   updatePosition(this.getCenter().lat(), this.getCenter().lng()); // update position display
});

see http://jsfiddle.net/gbqqzonr/

//Dragable Marker In Google Map....

var center = new google.maps.LatLng(-33.013803, -71.551498);

var map = new google.maps.Map(document.getElementById('mapBox'), {
    zoom: 18,
    center: center,
    mapTypeId: google.maps.MapTypeId.HYBRID
});

var myMarker = new google.maps.Marker({
    position: center,
    draggable: true,
    map: map
});

google.maps.event.addListener(myMarker, 'dragend', function () {
    map.setCenter(this.getPosition()); // Set map center to marker position
    updatePosition(this.getPosition().lat(), this.getPosition().lng()); // update position display
});

google.maps.event.addListener(map, 'drag', function () {
    myMarker.setPosition(this.getCenter()); // set marker position to map center
    updatePosition(this.getCenter().lat(), this.getCenter().lng()); // update position display
});

google.maps.event.addListener(map, 'dragend', function () {
    myMarker.setPosition(this.getCenter()); // set marker position to map center
    updatePosition(this.getCenter().lat(), this.getCenter().lng()); // update position display
});

function updatePosition(lat, lng) {
    document.getElementById('dragStatus').innerHTML = '<p> Current Lat: ' + lat.toFixed(4) + ' Current Lng: ' + lng.toFixed(4) + '</p>';
}
Comments